开发者

Ruby String class multiple methods and efficiency

开发者 https://www.devze.com 2023-02-05 12:58 出处:网络
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

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 upc开发者_运维知识库ase 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?


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))


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消