Reputation: 3299
This is kind of naïve question. But still asking.. Considering the following code:
func1(obj.state)
func2(obj.state)
func3(obj.state)
func4(obj.state)
Does replacing above code with below has any performance improvement or it doesn't matter at all (modern compilers can optimize these things themselves..?).
value = obj.state
func1(value)
func2(value)
func3(value)
func4(value)
If state was instead a big function that takes some time to compute, then surely second code would have better performance. I'm asking in the case when its just a state.
I thought of this because, in first case it has first go to the reference of object, and then it has to go to reference pointed by state. But in second case it can directly go to the reference pointed by value. It is a tradeoff between space and time.
Also does this differ from language to language?
Upvotes: 0
Views: 28
Reputation: 11311
Question to you: does better performance matter to you if the result is not correct?
The first code fragment uses latest state for each function call, the second - the same state for all calls. If you know that the state doesn’t change, and if the compiler doesn’t know that - the second fragment is better. Otherwise use the first.
Upvotes: 2