Why is "this.var" less efficient than "array.length"?
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++)
开发者_StackOverflow(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?
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.
精彩评论