Reputation: 26997
I was looking through the Ruby source code and I can't seem to find a answer to my question:
If I call multiple methods on a string (str.upcase.reverse
), does Ruby optimize this query? The code for upcase
basically loops over the string and coverts each letter to its uppercase value and the reverse
reverses the string. Does Ruby combine these (or any other combinable combinations) so that it will reverse AND capitalize at the same time O(n)
instead of looping over each character in the string twice?
Upvotes: 1
Views: 347
Reputation: 12165
No, there is no optimization like you describe, but feel free to write a method that performs a reverse+capitalize in one loop.
Definitely check out the Benchmark standard library. When writing optimizations, always benchmark, never assume :)
PS: reverse.upcase
is still O(n). Big O notation disregards constants.
Upvotes: 1
Reputation: 14222
The optimization you are hoping for will not happen. The reverse
method is being called on a string (the result of str.upcase
). Note that the resulting behavior is still O(n)
however (O(2n)
is O(n)
)
Upvotes: 2