Is the &method(:method_name) idiom bad for performance in Ruby?

前端 未结 5 698
既然无缘
既然无缘 2020-12-03 11:20

I\'ve recently come across the &method(:method_name) syntax. (This uses the Object#method method - RDoc link) For example,

[5,         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 12:08

    Since Rubinius is the most advanced and most aggressively optimizing Ruby implementation, I asked this question on the Rubinius mailinglist, and here's what Evan Phoenix had to say:

    Your assumption that it could be the same as a block is, I'm sad to say, dead wrong. There reason you don't see Method#to_proc and such in profiling is 2 fold:

    1. Most (all?) MRI profilers do not show methods that MRI defines in C, so they'd never show up.
    2. The mechanism for activating a method that has been turned into a Proc is all in C, so the overhead is invisible on the invocation side too.

    Your point about the arty differences are right on. Additionally, your thinking that a VM could easily optimize it into a block is quite wrong. Object#method is a not something that would be detected and optimized away. Additionally, even with runtime optimizations, something like escape analysis is still required since #method returns a Method object that you'd have to see inside and extract the information from. On the invocation side, the invoked method can only do something special with the block in the case of block inlining, an optimization that only Rubinius has.

    So to get to your questions:

    1. Does Rubinius optimize this code? No. Could it? Yes, but it's hardly easy.
    2. In time it could, yes.
    3. In time it should, yes.

    Note: the questions he refers to in the last paragraph are:

    1. Does Rubinius currently optimize such point-free code?
    2. If it doesn't, could it?
    3. If it could, should it?

提交回复
热议问题