Skip to content

Instantly share code, notes, and snippets.

@franckverrot
Last active August 29, 2015 14:01
Show Gist options
  • Save franckverrot/f291eb5e90f1d2357548 to your computer and use it in GitHub Desktop.
Save franckverrot/f291eb5e90f1d2357548 to your computer and use it in GitHub Desktop.
String#<< vs String#+=
# More details about the 23 value
# https://github.com/ruby/ruby/blob/e279eca4bdf1e4364308aee2ca504bbdf2b5d221/include/ruby/ruby.h#L824-836
#
require 'benchmark'
N = 1_000_000
Benchmark.bmbm do |bm|
bm.report("s_23chr +=") { N.times { s_23chr = "xxxxxxxxxxxxxxxxxxxxxx"; s_23chr += "x" } }
bm.report("s_23chr <<") { N.times { s_23chr = "xxxxxxxxxxxxxxxxxxxxxx"; s_23chr << "x" } }
bm.report("s_24chr +=") { N.times { s_24chr = "xxxxxxxxxxxxxxxxxxxxxxx"; s_24chr += "x" } }
bm.report("s_24chr <<") { N.times { s_24chr = "xxxxxxxxxxxxxxxxxxxxxxx"; s_24chr << "x" } }
end
# Results
# =======
#
# ---- MRI ----
# λ ruby test.rb
# Rehearsal ----------------------------------------------
# s_23chr += 0.530000 0.000000 0.530000 ( 0.588668)
# s_23chr << 0.520000 0.000000 0.520000 ( 0.566326)
# s_24chr += 0.950000 0.010000 0.960000 ( 1.166513)
# s_24chr << 0.940000 0.000000 0.940000 ( 1.036913)
# ------------------------------------- total: 2.950000sec
#
# user system total real
# s_23chr += 0.530000 0.000000 0.530000 ( 0.593657)
# s_23chr << 0.520000 0.000000 0.520000 ( 0.625555)
# s_24chr += 0.950000 0.010000 0.960000 ( 1.106309)
# s_24chr << 0.940000 0.000000 0.940000 ( 1.068339)
# ---- Rubinius ---
# Rehearsal ----------------------------------------------
# s_23chr += 2.974743 0.036307 3.011050 ( 2.560110)
# s_23chr << 0.515138 0.007274 0.522412 ( 0.496798)
# s_24chr += 1.097682 0.015315 1.112997 ( 1.003511)
# s_24chr << 0.431469 0.008770 0.440239 ( 0.487722)
# ------------------------------------- total: 5.086698sec
#
# user system total real
# s_23chr += 0.915017 0.013043 0.928060 ( 0.967486)
# s_23chr << 0.402066 0.005867 0.407933 ( 0.445658)
# s_24chr += 0.732000 0.015172 0.747172 ( 0.825339)
# s_24chr << 0.333328 0.007682 0.341010 ( 0.352961)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment