开发者

Avoiding getfield opcode

In Java's String class, the trim method contains this:

int off = offset;      /* avoid getfield opcode */
char[] val = value;    /* avoid ge开发者_如何学运维tfield 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?


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.)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜