Ruby is a language with many aliases in method names.
For example, map
and collect
of Enumerable
are aliases, and the same result can be obtained by using either of them.
Therefore, which one to use became a matter of taste, and even the words "map school" and "collect school" were born.
So when a method has multiple names, is it really the same no matter which one you use? There is an example that cannot be said so.
Integer has a method that "returns the number of receivers plus one" and has two names, next
and succ
.
Since it is an alias, the function is of course the same, but the speed is different.
Install a benchmark test gem called benchmark_driver and install it.
next-succ.yaml
benchmark:
- 1.next
- 1.succ
Prepare a YAML file called
benchmark-driver next-succ.yaml
Let's try. Result is
1.succ: 134563685.5 i/s
1.next: 8751120.9 i/s - 15.38x slower
As you can see, there was a speed difference of 15 times.
Experiment environment:
ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-darwin17]
The reason why this happens is that there is some optimization only in succ
on RubyVM.
So should we absolutely use succ
instead of next
?
It depends.
Looking at the above results, even Integer # next
can be executed more than 8 million times per second.
Even if you use it in a loop that goes around a lot, most practical code will be much lighter than the rest of the process in the loop.
In real code rather than microbenchmarks, the difference between succ
and next
may not often affect processing speed.