reox
reox

Reputation: 5227

performance by creating new variable

i want to write my java programm as performant as i can so i'm reducing everything to have best performance... In the programm a method will called apprx. 9million times. there i have to calculate somthing, just subtracting two integers and these are needed twice. so my question is, what is faster: initialize new integer with the result of calculation or just calculate the values twice? e.g:

int result = a-b;
methodToCall(result, foo, bla);
otherMethod(result, bla, foo);

or

methodToCall(a-b, foo, bla);
otherMethod(a-b, bla foo);

i cant see a difference directly, but sometimes its with the first method a little bit faster... in general: is the first method always better? e.g when using other types of calculation (more complex). Is the java compiler or the jvm doing something with it to optimize it, e.g. see that i do the same calculation twice and doing it only once and cache the result by its own?

Upvotes: 1

Views: 174

Answers (3)

Alan Escreet
Alan Escreet

Reputation: 3549

The first will theoretically be faster.

In the second, the JVM will not only calculate a-b twice, but will also temporarily assign storage for the result twice before passing it to the two method calls.

I just ran tests for these cases 100 million times and came up with just 10-15ms difference between them with the first being faster. My test results will be skewed because a and b are constants, but it nevertheless seems to confirm the theory.

Upvotes: 4

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

Simply measure the time. Without knowing the facts you can't do any conclusions. See this question about the tools.

If the difference is hard to notice, always prefer the well readable code.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533710

The JVM may optimise the code in the second case to act like the first. However if it doesn't it may cost you 1 clock cycle which might be about 3 ms (if you call it 9 million times on a 3 GHz processor)

I prefer the first form because it reduces repetition which for me makes it easier to read. If your expression is more expensive, it could make more of a difference.

Upvotes: 1

Related Questions