When passing objects as parameters, are they passed by reference?

后端 未结 5 559
名媛妹妹
名媛妹妹 2021-01-12 12:01

Is there any performance implications if I do either of these:

def do_something(user, article)
...
end

versus

def do_someth         


        
相关标签:
5条回答
  • 2021-01-12 12:18

    Re: https://stackoverflow.com/a/6528257 (I didn't have enough reputation to comment at time of writing)

    Ah, but Jörg, if you actually manipulate the argument, instead of assigning a new object to it, the method behaves differently. Using .replace instead of = gives you this:

    def is_Ruby_pass_by_value_or_reference?(parameter)
      parameter.replace 'Ruby is pass-by-reference.'
    end
    
    var = 'Ruby is pass-by-value.'
    
    is_Ruby_pass_by_value_or_reference?(var)
    
    puts var
    # Ruby is pass-by-reference.
    

    In fact, let's elaborate just a little more, just to show the difference:

    def is_Ruby_pass_by_value_or_reference?(parameter)
      parameter.replace 'Ruby is pass-by-reference.'
      parameter = "This assigns a whole new object to 'parameter', but not to 'var'."
      puts parameter
    end
    
    var = 'Ruby is pass-by-value.'
    
    is_Ruby_pass_by_value_or_reference?(var)
    # This assigns a whole new object to 'parameter', but not to 'var'.
    
    puts var
    # Ruby is pass-by-reference.
    
    0 讨论(0)
  • 2021-01-12 12:19

    No, Ruby never passes by reference. Ruby is pass-by-value. Always. No exceptions.

    def is_Ruby_pass_by_value_or_reference?(parameter)
      parameter = 'Ruby is pass-by-reference.'
    end
    
    var = 'Ruby is pass-by-value. Always. No exceptions.'
    
    is_Ruby_pass_by_value_or_reference?(var)
    
    puts var
    # Ruby is pass-by-value. Always. No exceptions.
    

    If Ruby were pass-by-reference, this would print Ruby is pass-by-reference.

    0 讨论(0)
  • 2021-01-12 12:32

    Yes

    Both method calls will take about the same amount of time.

    (It's good to be aware of performance consequences and you asked a reasonable question, but even so, the standard disclaimer1 about early optimization technically applies.)


    1. First, make program work. Then, profile. Finally, and maybe, optimize.
    Donald Knuth said: We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

    0 讨论(0)
  • 2021-01-12 12:32

    For example, I would go with the _id variant. I prefer to always be able to get the correct state of my objects. It's never fun to work with stale ones.

    0 讨论(0)
  • 2021-01-12 12:40

    Well everything is an Object in ruby (everything inherits from Object) and ruby always passes objects by ref so both of your examples are passing by reference!

    0 讨论(0)
提交回复
热议问题