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.
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.
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.
Code: https://gist.github.com/1562617In 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(:+):
Code: https://gist.github.com/1562994+= is not append
is the equivalent to: 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. Code: https://gist.github.com/1563290