Avoiding getfield opcode

匿名 (未验证) 提交于 2019-12-03 02:11:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!