java - Which one is better in calling a function: two times or storing the result in a variable? -
i have got doubt many times, didn't figure out correct soltion. time want clear off. have situation like
1. string snumber="ksadfl.jksadlf"; if(snumber.lastindexof('.')>0) //do ... ... if(snumber.lastindexof('.')>1) //do ... 2. int index = snumber.lastindexof('.'); if(index>0) //do ... ... if(index>1) //do ...
what trade offs between first way , second way? 1 better in storing result in variable or calling function 2 times?
in example, 2nd form better (in plausible situations1) performance perspective, , (imo) more readable.
in general, there couple of trade-offs consider:
- is readability more important efficiency?
- how of "performance hit" call method twice versus once?
also, need consider cases method may have side-effects, , whether may give different answer on 2 successive calls. in cases, calling method twice semantically different calling once , storing result in temporary variable.
1 - index
variable makes stack frame 1 word larger. doesn't matter, if code in recursive method gets called in recursive fashion, 1 word multiplied number of nested calls result in stackoverflowerror
.
Comments
Post a Comment