Skip to content

Commit

Permalink
Use @+ instead of dup for duplicating strings
Browse files Browse the repository at this point in the history
This is faster and a bit cheaper on the memory side as well.

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  gem "benchmark-ips"
  gem "benchmark-memory"
end

Benchmark.ips do |x|
  x.report("dup") { "foo".dup }
  x.report("@+") { +"foo" }

  x.compare!
end

Benchmark.memory do |x|
  x.report("dup") { "foo".dup }
  x.report("@+") { +"foo" }

  x.compare!
end

Warming up --------------------------------------
                  dup   642.978k i/100ms
                  @+     1.350M i/100ms
Calculating -------------------------------------
                  dup      6.646M (± 0.6%) i/s -     33.435M in   5.030737s
                  @+     13.503M (± 0.7%) i/s -     67.515M in   5.000186s

Comparison:
                  @+: 13503099.2 i/s
                  dup:  6646345.1 i/s - 2.03x  slower

Calculating -------------------------------------
                  dup    80.000  memsize (     0.000  retained)
                          2.000  objects (     0.000  retained)
                          1.000  strings (     0.000  retained)
                  @+    40.000  memsize (     0.000  retained)
                          1.000  objects (     0.000  retained)
                          1.000  strings (     0.000  retained)

Comparison:
                  @+:         40 allocated
                  dup:         80 allocated - 2.00x more
  • Loading branch information
nirebu committed Mar 21, 2023
1 parent 1720689 commit 81f57d7
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion lib/datadog/core/utils/safe_dup.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def dup
end

def self.frozen_or_dup(v)
v.frozen? ? v : v.dup
v.frozen? ? v : +v
end
end
end
Expand Down

0 comments on commit 81f57d7

Please sign in to comment.