Reputation: 65
In my Java application I have some methods that always return the same thing. So, Is JIT able to detect these methods and optimize the performance (clone the result instead of calculate it or other way) ?
Example of candidate method for the optimisation :
private List<String> get() {
return Arrays.asList(Operation.values()).stream().map(Object::toString).collect(Collectors.toList());
}
In my point of view it is not possible, but I am no sure.
Upvotes: 1
Views: 368
Reputation: 98314
Common subexpression elimination (CSE) is a well-known compiler optimization to avoid recalculation of identical expressions. In general, JVM is capable of such optimization.
But this is not your case. The given get()
method does not return the same thing.
First of all, assuming that Operation
is enum type, Operation.values()
returns new array each time. It must return a new object to protect the original array from modification.
Collectors.toList()
in its current implementation also returns a new ArrayList
each time. JVM cannot do anything about this allocation since the returned object is visible outside.
Upvotes: 3