tags:

views:

96

answers:

1

When I watched the "Dalvik VM Internals" talk, I had a question about one of the slides about wise loops. Here is two of the seven loops on that slide:

(4) for (int i = 0; i < array.length; i++)

(5) for (int i = 0; i < this.var; i++)

and the speaks said (4) is more efficient than (5). "array" is just an Array object.

My question is what exactly does "this.var" do that makes it is more expensive than retrieving a member variable from an object?

+2  A: 

I think you need to recheck what is actually said. Slide 54 seems to be talking about (2) and (3) and implying that they are better than all of the others. (I cannot listen to the audio stream to check what is actually said ...)

Off the top of my head, in (4) if the array local variable is not assigned in the loop body, then array.length can be read from memory once and held in a register for the loop duration. (An array's length can never change ... and I'm assuming that array is a local not a field of this.)

By constrast, in (5) this.var can potentially be altered by another thread while the loop is running, so (depending on how Davlik implemented the Java memory model) it may need to be refetched each time around the loop.

But this depends on how Davlik handles this. The Java Language Spec does not require the implementation to refetch, unless this.var is declared as volatile. But whether it does is an implementation detail that could (presumably) change.

Stephen C
The speaker said the efficiency degrades from (1) to (7), i.e. (1) is the most efficient and (7) is the least. You're right (2) and (3) are better than (4) - (7). As for (4) vs. (5), I think you are probably right on the point that "array" may be a local variable but "this.var" is shared by threads. It depends on the memory model that Dalvik implements.
X. Ma
Also, "array.length" turns into an "array-length" instruction, while "this.var" is a field lookup. The former can be faster than the latter.
fadden
@fadden - in theory it could be slower too. In reality, the code speed depends on the optimizations performed by the Davlik JIT compiler on the platform that the application is running. The only thing we can say definitively is that (4) is easier for the JIT to optimize than (5); see my answer.
Stephen C