Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid indirection and redundant method calls

Tags:

java

android

I am currently reviewing a PullRequest that contains this:

-        for (int i = 0; i < outgoingMassages.size(); i++) {
+        for (int i = 0, size = outgoingMassages.size(); i < size; i++) 

https://github.com/criticalmaps/criticalmaps-android/pull/52

somehow it feels wrong to me - would think that the vm is doing these optimisations - but cannot really say for sure. Would love to get some input if this change can make sense - or a confirmation that this is done on VM-side.

like image 260
ligi Avatar asked Oct 05 '15 10:10

ligi


Video Answer


2 Answers

No, is not sure that the VM will change your code from

 -        for (int i = 0; i < outgoingMassages.size(); i++) {

to

 +        for (int i = 0, size = outgoingMassages.size(); i < size; i++) 

In your for loop it is possible that the outgoingMassages will change its size. So This optimization can't be applied by the JVM. Also another thread can change the outgoingMassages size if this is a shared resource.

The JVM can change the code only if the behaviour doesn't change. For example it can substitute a list of string concatenations with a sequence of append to StringBuilder, or it can inline a simple method call, or can calculate a value out of the loop if it is a constant value.

like image 71
Davide Lorenzo MARINO Avatar answered Sep 27 '22 19:09

Davide Lorenzo MARINO


The VM will not do this optimizations. Since it is possible that the size()-Method does not return the same result each call. So the method must be called each iteration.

However if size is a simple getter-method the performance impact is very small. Probably not measurable. (In few cases it may enable Java to use parallelization which could make a difference then, but this depends on the content of the loop).

The bigger difference may be to ensure that the for-loop has an amount of iterations which is known in advance. It doesn't seem make sense to me in this example. But maybe the called method could return changing results which are unwanted?

like image 40
Denis Lukenich Avatar answered Sep 27 '22 21:09

Denis Lukenich