Is there any performance implications 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.
Objects are passed by reference and primitive types are passed by value. A correct statement would be: Object references are passed by value, as are primitive types. Thus, Java passes by value, not by reference, in all cases.
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.
To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.
Java always passes arguments by value, NOT by reference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With