Skip to content

Instantly share code, notes, and snippets.

@joel
Created October 17, 2012 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joel/3904601 to your computer and use it in GitHub Desktop.
Save joel/3904601 to your computer and use it in GitHub Desktop.
Benchmark of String concatenation
require 'benchmark'
N = 70000
Benchmark.bmbm do |x|
x.report('foo + bar') { N.times {
'foo' + 'bar'
} }
x.report('#{foo}#{bar})') { N.times {
"#{'foo'}#{'bar'}"
} }
x.report('foo << bar') { N.times {
'foo' << 'bar'
} }
x.report('foo.concat(bar)') { N.times {
'foo'.concat('bar')
} }
end
# Rehearsal ---------------------------------------------------
# foo + bar 0.030000 0.000000 0.030000 ( 0.027416)
# #{foo}#{bar}) 0.010000 0.000000 0.010000 ( 0.013595)
# foo << bar 0.020000 0.000000 0.020000 ( 0.025066)
# foo.concat(bar) 0.030000 0.000000 0.030000 ( 0.031215)
# ------------------------------------------ total: 0.090000sec
#
# user system total real
# foo + bar 0.030000 0.000000 0.030000 ( 0.026326)
# #{foo}#{bar}) 0.010000 0.000000 0.010000 ( 0.012222)
# foo << bar 0.020000 0.000000 0.020000 ( 0.025858)
# foo.concat(bar) 0.020000 0.000000 0.020000 ( 0.033805)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment