When passing objects as parameters, are they passed by reference?
Is there any performance implica开发者_如何学编程tions if I do either of these:
def do_something(user, article)
...
end
versus
def do_something(user_id, article_id)
..
end
I prefer passing objects as I might need other attributes down the road.
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.
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.
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.
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.
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!
精彩评论