Skip to content

Comment on Never create Ruby strings longer than 23 charactersparent

Comments

I was curious, so I benchmarked this with Ruby MRI. join('') beat reduce(:+) even on two strings, but is twice as fast only on four or more strings.

   $ ruby -v
   ruby 1.8.7 (2010-01-10 patchlevel 249) [universal-darwin11.0]
   $ ruby benchmark.rb
         user     system      total        real
   add  2  0.390000   0.000000   0.390000 (  0.385910)
   join 2  0.300000   0.000000   0.300000 (  0.305812)

   add  3  0.530000   0.000000   0.530000 (  0.527388)
   join 3  0.320000   0.010000   0.330000 (  0.329390)

   add  4  0.720000   0.000000   0.720000 (  0.720500)
   join 4  0.350000   0.000000   0.350000 (  0.353237)
Code: https://gist.github.com/1562617

In case you were wondering why, it is most likely* because `#join` is appending to a single string, whereas the `#reduce` call is creating intermediate strings for each step of the fold.

* I'd have to check the implementation of `#join` to be sure.

I thought so too, but appending to a single string does even worse than reduce(:+):

  add 2  0.390000   0.000000   0.390000 (  0.390529)
  +=  2  0.540000   0.000000   0.540000 (  0.537450)

  add 3  0.530000   0.000000   0.530000 (  0.534131)
  +=  3  0.760000   0.000000   0.760000 (  0.752280)

  add 4  0.660000   0.000000   0.660000 (  0.668154)
  +=  4  0.960000   0.000000   0.960000 (  0.954727)
Code: https://gist.github.com/1562994

+= is not append

  str += append_str
is the equivalent to:
  str.dup << append_str
That is, it copies the string and then appends to the copy. Benchmarking the speed of a true append is difficult because in order to preserve the original string in the benchmark you must dup it anyhow (done here outside of the bench.report block). However, the bigger the strings get, the more pronounced the advantage of appending is.
                user     system      total        real
  add  2      0.260000   0.000000   0.260000 (  0.263414)
  join 2      0.320000   0.000000   0.320000 (  0.325341)
  append 2    0.230000   0.010000   0.240000 (  0.235669)

  add  3      0.500000   0.000000   0.500000 (  0.497219)
  join 3      0.840000   0.020000   0.860000 (  0.866401)
  append 3    0.260000   0.010000   0.270000 (  0.268676)

  add  4      0.360000   0.040000   0.400000 (  0.397778)
  join 4      0.970000   0.030000   1.000000 (  0.997321)
  append 4    0.280000   0.000000   0.280000 (  0.281020)

  add  5      0.460000   0.000000   0.460000 (  0.454780)
  join 5      0.910000   0.030000   0.940000 (  0.946600)
  append 5    0.330000   0.000000   0.330000 (  0.336214)
Code: https://gist.github.com/1563290
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.