Skip to content

Instantly share code, notes, and snippets.

@mohnish
Created March 29, 2016 20:15
Show Gist options
  • Save mohnish/1bae41798f1a956917ec8b0911e039bb to your computer and use it in GitHub Desktop.
Save mohnish/1bae41798f1a956917ec8b0911e039bb to your computer and use it in GitHub Desktop.
benchmark string concat vs append vs +
require 'benchmark/ips'
n = 100_000
Benchmark.ips do |x|
x.config(time: 5, warmup: 2)
x.report('concat') do |times|
foo = ""
n.times do |i|
foo.concat("#{i}")
end
end
x.report('append') do |times|
foo = ""
n.times do |i|
foo << "#{i}"
end
end
x.report('+') do |times|
foo = ""
n.times do |i|
foo += "#{i}"
end
end
x.compare!
end
@mohnish
Copy link
Author

mohnish commented Mar 29, 2016

Warming up --------------------------------------
              concat     2.000  i/100ms
              append     2.000  i/100ms
                   +     1.000  i/100ms
Calculating -------------------------------------
              concat     54.165  (± 7.4%) i/s -    270.000 
              append     54.400  (± 5.5%) i/s -    272.000 
                   +      0.097  (± 0.0%) i/s -      1.000  in  10.351940s

Comparison:
              append:       54.4 i/s
              concat:       54.2 i/s - same-ish: difference falls within error
                   +:        0.1 i/s - 563.15x slower

@mohnish
Copy link
Author

mohnish commented Mar 29, 2016

Darwin mt-4.local 15.4.0 Darwin Kernel Version 15.4.0: Fri Feb 26 22:08:05 PST 2016; root:xnu-3248.40.184~3/RELEASE_X86_64 x86_64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment