I have got this doubt many times, but didn't figure it out the correct soltion. This time I want clear it off. I have situation like
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 are the trade offs between first way and second way? which one is better in storing the result in a variable or calling the function two times?
twice depends on your method. If it is a simple getter, the JVM might optimize the call and directly use the value so storing it in a local variable does not make a difference. If it is a more complex method, e.g. a query to the database, I would definitely store the result in a local variable.
Lines 8 and 9 - Once the function has been defined, we may call it as many times as we like and it will execute those commands.
In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.
A Function is the Python version of the routine in a program. Some functions are designed to return values, while others are designed for other purposes. We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.
In this example, the 2nd form is better (in most plausible situations1) from a performance perspective, and (IMO) more readable.
In general, there are a couple of trade-offs to consider:
Also, you also need to consider the cases where the method may have side-effects, and whether it may give a different answer on two successive calls. In those cases, calling the method twice is semantically different to 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 in a recursive method that gets called in a deeply recursive fashion, that 1 extra word multiplied by a number of nested calls could result in a StackOverflowError
.
Since the question only talks about 2 lean lastIndexOf
calls, there's actually little difference between the two. If it's a remote call via a proxy or something that does a database hit, then storing the method result into a variable would see you some improvement.
The good thing about calling the method again is that you'll always get the latest value of the index, in case it was manipulated somewhere in the earlier blocks. On most cases, #2 will be the right choice, but for your exact example above, it's #1.
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