Java – which is better when calling a function: twice or storing the result in a variable?
I doubted this problem many times, but I couldn't find the right solution I'll clear it this time I like something
1.
String sNumber="ksadfl.jksadlf";
if(sNumber.lastIndexOf('.')>0)
//do something
...
...
if(sNumber.lastIndexOf('.')>1)
//do something
...
2.
int index = sNumber.lastIndexOf('.');
if(index>0)
//do something
...
...
if(index>1)
//do something
...
What is the trade-off between the first approach and the second approach? Which better store the result in a variable or call the function twice?
Solution
In this example, from a performance point of view, the second form is better (in most reasonable cases 1), and (IMO) is more readable
In general, several trade-offs need to be considered:
>Is readability more important than efficiency? > What is the "performance penalty" of calling this method twice compared to "once"?
In addition, you need to consider the possible side effects of a method and whether it can give different answers in two consecutive calls In these cases, calling a method twice is semantically different from calling it once and storing the result in a temporary variable
1 - the index variable makes the stack frame 1 word larger Normally, this doesn't matter, but if the code is a recursive method called recursively, 1 extra word multiplied by some nested calls may cause stackoverflowerror
