Small challenge: Reverse a string in ruby without using the standard
library #reverse method.
There were some interesting comparisons on stackoverflow . I decided to write my own solution and run some benchmarks with ruby 2.2.0.
My reverse function turned out similiar to one of the stackoverflow solutions,
which used Enumerable#reduce method combined with #unshifting
(enqueue) characters into a new array.
However, you can check the stackoverflow discussion as to why this isn’t the most
efficient solution (hint: what’s happening when you #unshift array?).
For practice, I also tried another implementation with #tap method.
Here’s some more examples:
And some benchmarks for comparison:
Results
Overall, it looks like the standard library #reverse method is
signficantly faster.
The reverse with #tap didn’t seem to have much of a performance hit compared to the other reverse method.
And lastly, I was expecting the reverse function (using #unshift) to take much
longer than it did. Supposedly, the #unshift causes the solution to be
O(n^2) since characters have to be shifted in array for each iteration. I’ll have to investigate this further.
EDIT: Checked with @Marc-André Lafortune on stackoverflow, and it looks like “Ruby now optimizes for successive unshifts and pre allocates some memory to avoid moving all elements”. This helps to explain the different benchmark results using ruby 2.2.0.