Reputation: 19759
I have an inline member function defined under class MyClass
int MyClass::myInlineFunction();
This function is called from several places in my code.
There are two ways to call this function
Case 1: Using this every time the function is called.
mobj->myInlineFunction() ;
Case 2: Assign the result of this function to a variable and use it for subsequent accesses
var = mobj->myInlineFunction() ;
Which one should be preferred??
Upvotes: 0
Views: 1609
Reputation: 6231
I would use Case 2 even if performance is not a problem. If all you care is the result of this function, then assigning it to a variable allows you later to easily switch to another method of obtaining this result.
Upvotes: 1
Reputation: 208353
Optimizing without knowing what or where usually ends up with more complex code that is not faster than the original.
To me the criteria to determine what solution to use is not based in the information that you provide.
Upvotes: 0
Reputation: 7157
Unfortunatly there isn't one simple answer, it depends on the function.
If the function is trivial, something like { return 6; }, just call it each time. The compiler will inline the call and remove the code. You should find no difference between assigning it to a variable, or not.
If the function is more complex, then it might be worth assigning it to a variable. Is the value constant throughout the program? Then maybe add to the class a static member which contains the value?
Upvotes: 0
Reputation: 96869
I can not understand the relation between inlining the function and assigning it to a function pointer as I understand.
EDIT :: Thanks Ahmed,
It depends actually and one can not always be used instead of the other way.
Again, the first way is clearer for me at least, if both work.
Upvotes: 0
Reputation: 7238
If the function returns the same result for every call, you have to use case 2 as it does not make sense to use case 1 even if it is inline function
Upvotes: 0
Reputation: 7841
The decision on whether to hold onto a return value or to recall the function again, should not be based on whether the function is inlined or not - as this is an implementation detail that may change over the lifetime/evolution of the class. As a rule of thumb I would always hang onto the return value if it does not make the code too complicated, as you do not know as a user of a class, what the cost of the function is - and what is cheap today could be expensive tomorrow. So I would go with Case 2.
Upvotes: 1
Reputation: 36987
Case 2 can give you a lot of performance, if the function does something that takes some time. Choose it if
Upvotes: 3