Michael
Michael

Reputation: 14218

Java compiler optimisation

Do I need to worry about performance in the case below and save the result of the expensive call, or does the compiler recognise it can do the expensive call once?

String name;
if (object.expensiveCall() != null) {
  name = object.expensiveCall().getName();
}

Upvotes: 1

Views: 248

Answers (5)

Oleg Mikheev
Oleg Mikheev

Reputation: 17444

In future you can compile and decompile your class back with JAD to see compiler optimizations.

In your case it doesn't optimize anything.

Upvotes: 0

Mysticial
Mysticial

Reputation: 471209

You're looking for something called memoization. This question suggests that Java can't do it natively.

In general, memoization is only possible if the compiler/JIT can prove that the function has no side-effects. So I wouldn't count on it.

But is it really that hard to just save the result?

String name;
ObjectType temp = object.expensiveCall();
if (temp != null) {
    name = temp.getName();
}

Upvotes: 1

Gareth Boden
Gareth Boden

Reputation: 318

The compiler will not (in general) do the call just once as it may have side effects, or may be volatile in its result - it couldn't possibly know when you wanted it to ignore a second call and when you wanted it to actually make the call again. You need to save the result:

final ExpensiveCallResult nullableResult = object.expensiveCall();
String name;
if (nullableResult != null) {
  name = nullableResult.getName();
}

Upvotes: 2

Paul Bellora
Paul Bellora

Reputation: 55213

No, you will need to rewrite it to only make the call once:

String name;
MyResult result = object.expensiveCall();
if (result != null) {
  name = result.getName();
}

You can also shorten the syntax to make the assignment and check in the same line:

String name;
MyResult result;
if ((result = object.expensiveCall()) != null) {
  name = result.getName();
}

Upvotes: 0

A.H.
A.H.

Reputation: 66213

How could the Java compiler know, that expensiveCall has no side effects? In the general case - it cannot. Also: You might recompile the class of object anytime without recompiling your current class. And what would happen if expensiveCall has got side effects now? No way for automatic optimization.

BTW: The JIT-Compiler at runtime might have more information. But expensive calls are usually not considered for inlining and hence also not to further optimization steps.

Upvotes: 0

Related Questions