可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
In Java's String class, the trim method contains this:
int off = offset; /* avoid getfield opcode */ char[] val = value; /* avoid getfield opcode */
I'm a bit puzzled by the comment "avoid getfield opcode"...
What does this mean? (I take it this avoids the use of getfield in the bytecode but why is this a Good Thing [TM]?)
Is it to prevent object creation in case trim doesn't do anything (and hence this is returned) or?
回答1:
My guess is that the point is to copy the values into local variables once, to avoid having to fetch the field value repeatedly from the heap for each iteration of the loop in the next few lines.
Of course, that begs the question as to why the same comment hasn't been applied on the "len" local variable. (I'd also expect the JIT to avoid refetching anyway, especially as the variables are final.)
回答2:
getfield
is used to get the member variable of a class.
As you can see from the remaining code:
while ((st < len) && (val[off + st] <= ' ')) { st++; } while ((st < len) && (val[off + len - 1] <= ' ')) { len--; }
So when you're in a loop, it has to execute getfield
every time you reference value
or offset
. You can incur a large performance-hit if the loop runs for a long time (because every time the loop-condition is tested, a getfield
is exeuted for both offset
and value
). So by using the local variables off
and val
, you reduce the performance hit.