Performance: calling a method recursively vs. using conditional logic - java

I call a method with a variable x, I make some checks and if some conditions are true I have to execute part of the same method with a different variable value.
What is more effective?
to call the method again (recursion), or
to change the value of my variable and leave the program to execute the following lines of the method?
In both cases i can make it work but what is the more efficient way?
For the second case, I use an if statement on top. I read the value I want and then the following if statements are executed using this value.
public void mymethod(x){
if (con){
x = something;
}
if (con2){
//do something
} else if(con3) {
//do something
}
}

As Dave said, you probably should not be concerned at all about such micro-optimizations. The best thing to do is to write your code in such a way that it is easiest to read and understand. The best approach in my opinion would be to move the "do something" part into a separate function, and pass to it all the parameters that it needs in order to do its job.
If you really want to get down to efficiency talk, be advised that modern systems tend to rely heavily on caching, so many approaches to performance which used to work in the past do not actually constitute improvements anymore. On the contrary, they worsen things.

it is more efficient to modify the value of x and continue the method execution. The reason is simple. When you call a function, the caller state must be saved (into a stack) then local variables of the called method are read and so the called method is executed. So, being already in the called method myMethod it'd be "cheaper" to access the variable x to modify its value and then continue

Related

Prefer Setters(Lombok) or normal assign [duplicate]

I have a getter that returns a String and I am comparing it to some other String. I check the returned value for null so my ifstatement looks like this (and I really do exit early if it is true)
if (someObject.getFoo() != null && someObject.getFoo().equals(someOtherString)) {
return;
}
Performancewise, would it be better to store the returned String rather than calling the getter twice like this? Does it even matter?
String foo = someObject.getFoo();
if (foo != null && foo.equals(someOtherString)) {
return;
}
To answer questions from the comments, this check is not performed very often and the getter is fairly simple. I am mostly curious how allocating a new local variable compares to executing the getter an additional time.
It depends entirely on what the getter does. If it's a simple getter (retrieving a data member), then the JVM will be able to inline it on-the-fly if it determines that code is a hot spot for performance. This is actually why Oracle/Sun's JVM is called "HotSpot". :-) It will apply aggressive JIT optimization where it sees that it needs it (when it can). If the getter does something complex, though, naturally it could be slower to use it and have it repeat that work.
If the code isn't a hot spot, of course, you don't care whether there's a difference in performance.
Someone once told me that the inlined getter can sometimes be faster than the value cached to a local variable, but I've never proven that to myself and don't know the theory behind why it would be the case.
Use the second block. The first block will most likely get optimized to the second anyway, and the second is more readable. But the main reason is that, if someObject is ever accessed by other threads, and if the optimization somehow gets disabled, the first block will throw no end of NullPointerException exceptions.
Also: even without multi-threading, if someObject is by any chance made volatile, the optimization will disappear. (Bad for performance, and, of course, really bad with multiple threads.) And lastly, the second block will make using a debugger easier (not that that would ever be necessary.)
You can omit the first null check since equals does that for you:
The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
So the best solution is simply:
if(someOtherString.equals(someObject.getFoo())
They both look same,even Performance wise.Use the 1st block if you are sure you won't be using the returned value further,if not,use 2nd block.
I prefer the second code block because it assigns foo and then foo cannot change to null/notnull.
Null are often required and Java should solve this by using the 'Elvis' operator:
if (someObject.getFoo()?.equals(someOtherString)) {
return;
}

which one to choose between calling a function twice and storing the return value in a variable?

I have the following scenario.. and I come across the similar scenario many a times. Which is more preferable of the following two options?
Option-1:
String result = ( getDetails(...) == null ) ? "" : getDetails(...);
Option-2:
String returnValue = getDetails(...);
String result = ( returnValue == null ) ? "" : returnValue;
Which is more preferable and/or a good practice.?
Imho The second one is better because it's avoiding calling getDetails(...) method twice.
If you have to do that check for every call of getDetails then the best way would be getDetails method to return "" in cases when you return null.
Also calling the same method twice (which is probably idempotent in your case) is not a good practice even if it is very simple.
Please read this java-how-expensive-is-a-method-call. Main idea is don't do premature optimization, but you should get used to these simple cases when you can write better code
Option-2: is better
Option-1: Results in extra method call and such cases should always be avoided unless getDetails(...) is a getter method (a one liner method which returns something)
If you dig down to micro optimization, a method call generally results in
allocation of stack for the method variables
jumping the instruction set
which are couple of many overheads. As many say, such performance optimization should be left to Compiler and the code should be written to be more readable.
I'd prefer the second option because it is more readable, especially when using the ternary operator.
If it is a problem or not to call getDetails(...) 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.
Generally speaking: Care about code readability first! If you find performance problems later on, try optimizing then.
option-2 will be always optimized one what ever you wrote in the calling function.
Even if you are writing any in-build function or expression two times it will take fraction of section more than option-2.

Non-Void Method invoking without assigning return value

I tend to think that most of the time that variable returning methods are invoked to assign the return value to a variable, e.g.:
return1 = object.DoSomething();
Nevertheless, Apart from executing the method: What happens when a returning method is invoked and the return value is not assigned to a variable? e.g:
object.DoSomething();
Is this a good practice? Where does the return goes?
JB Nizet made a remarkable comment stating that methods are implemented for most cases. Kind of explains why this situation occurs often.
People do it all the time. If you don't need the variable that the method returns, than you don't have to assign it to anything.
Bear in mind, that sometimes the return variable has some meaning, like whether or not the operation was successful, and you might want to do something with that information
I think this is valid. Unless you have a need to use the return value further down, it is better to ignore (You can save from code review tools flag as un-used variables).
Method execution and flow stays same, only thing is you are ignoring return value.
It is good practice or not depends on situation, for example if you have requirement like how many rows update on executing query, you need to capture return value, but most of the times developers ignore this because they don't need to track how many records were updated.
The method is invoked in the same fashion as it would when the return value is assigned to a variable.
This is a perfectly acceptable practice, and is a necessity when invoking void methods, which do not return values (and therefore cannot be assigned to objects).
- Its always better to use void as a return type where you don't want to assign or use the returned value.
- It won't cause any problem in its efficiency but will be considered as loose programming.
That code will compile and run perfectly normal.

java - is initializing a temporary variable for simple getters better or not?

A very unimportant question about Java performance, but it made me wondering today.
Say I have simple getter:
public Object getSomething() {
return this.member;
}
Now, say I need the result of getSomething() twice (or more) in some function/algorithm. My question: is there any difference in either calling getSomething() twice (or more) or in declaring a temporary, local variable and use this variable from then on?
That is, either
public void algo() {
Object o = getSomething();
... use o ...
}
or
public void algo() {
... call getSomething() multiple times ...
}
I tend to mix both options, for no specific reason. I know it doesn't matter, but I am just wondering.
Thanks!
Technically, it's faster to not call the method multiple times, however this might not always be the case. The JVM might optimize the method calls to be inline and you won't see the difference at all. In any case, the difference is negligible.
However, it's probably safer to always use a getter. What if the value of the state changes between your calls? If you want to use a consistent version, then you can save the value from the first call. Otherwise, you probably want to always use the getter.
In any case, you shouldn't base this decision on performance because it's so negligible. I would pick one and stick with it consistently. I would recommend always going through your getters/setters.
Getters and setters are about encapsulation and abstraction. When you decide to invoke the getter multiple times, you are making assumptions about the inner workings of that class. For example that it does no expensive calculations, or that the value is not changed by other threads.
I'd argue that its better to call the getter once and store its result in a temporary variable, thus allowing you to freely refactor the implementing class.
As an anecdote, I was once bitten by a change where a getter returned an array, but the implementing class was changed from an array property to using a list and doing the conversion in the getter.
The compiler should optimize either one to be basically the same code.

Premature optimization in Java: when to use "x = foo.getX()" vs simply "foo.getX()"

When I find myself calling the same getter method multiple times, should this be considered a problem? Is it better to [always] assign to a local variable and call only once?
I'm sure the answer of course is "it depends".
I'm more concerned about the simpler case where the getter is simply a "pass-along-the-value-of-a-private-variable" type method. i.e. there's no expensive computation involved, no database connections being consumed, etc.
My question of "is it better" pertains to both code readability (style) and also performance. i.e. is it that much of a performance hit to have:
SomeMethod1(a, b, foo.getX(), c);
SomeMethod2(b, foo.getX(), c);
SomeMethod3(foo.getX());
vs:
X x = foo.getX();
SomeMethod1(a, b, x, c);
SomeMethod2(b, x, c);
SomeMethod3(x);
I realize this question is a bit nit-picky and gray. But I just realized, I have no consistent way of evaluating these trade-offs, at all. Am fishing for some criteria that are more than just completely whimsical.
Thanks.
The choice shouldn't really be about performance hit but about code readability.
When you create a variable you can give it the name it deserves in the current context. When you use a same value more than one time it has surely a real meaning, more than a method name (or worse a chain of methods).
And it's really better to read:
String username = user.getName();
SomeMethod1(a, b, username, c);
SomeMethod2(b, username, c);
SomeMethod3(username);
than
SomeMethod1(a, b, user.getName(), c);
SomeMethod2(b, user.getName(), c);
SomeMethod3(user.getName());
For plain getters - those that just returns a value - HotSpot inlines it in the calling code, so it will be as fast as it can be.
I, however, have a principle about keeping a statement on a single line, which very often results in expressions like "foo.getBar()" being too long to fit. Then it is more readable - to me - to extract it to a local variable ("Bar bar = foo.getBar()").
They could be 2 different things.
If GetX is non-deterministic then the 1st one will give different results than the 2nd
Personally, I'd use the 2nd one. It's more obvious and less unnecessarily verbose.
I use the second style if it makes my code more readable or if I have to use the assigned value again. I never consider performance (on trivial things) unless I have to.
That depends on what getX() actually does. Consider this class:
public class Foo {
private X x;
public X getX() { return x; }
}
In this case, when you make a call to foo.getX(), JVM will optimize it all the way down to foo.x (as in direct reference to foo's private field, basically a memory pointer). However, if the class looks like this:
public class Foo {
private X x;
public X getX() { return cleanUpValue(x); }
private X cleanUpValue(X x) {
/* some modifications/sanitization to x such as null safety checks */
}
}
the JVM can't actually inline it as efficiently anymore since by Foo's constructional contract, it has to sanitize x before handing it out.
To summarize, if getX() doesn't really do anything beyond returning a field, then there's no difference after initial optimization runs to the bytecode in whether you call the method just once or multiple times.
Most of the time I would use getX if it was only once, and create a var for it for all other cases. Often just to save typing.
With regards to performance, the compiler would probably be able to optimize away most of the overhead, but the possibility of side-effects could force the compiler into more work when doing multiple method-calls.
I generally store it locally if:
I'm will use it in a loop and I don't want or expect the value to change during the loop.
I'm about to use it in a long line of code or the function & parameters are very long.
I want to rename the variable to better correspond to the task at hand.
Testing indicates a significant performance boost.
Otherwise I like the ability to get current values and lower level of abstraction of method calls.
Two things have to be considered:
Does the call to getX() have any side effects? Following established coding patterns, a getter should not alter the object on which it is called, the in most cases, there is no side effect. Therefore, it is semantically equivalent to call the getter once and store the value locally vs. calling the getter multiple times. (This concept is called idempotency - it does not matter whether you call a method once or multiple times; the effect on the data is exactly the same.)
If the getter has no side effect, the compiler can safely remove subsequent calls to the getter and create the temporary local storage on its own - thus, the code remains ultra-readable and you have all the speed advantage from calling the getter only once. This is all the more important if the getter does not simply return a value but has to fetch/compute the value or runs some validations.
Assuming your getter does not change the object on which it operates it is probably more readable to have multiple calls to getX() - and thanks to the compiler you do not have to trade performance for readability and maintainability.

Categories