避免 getfield 操作码
在Java的String类中,trim方法包含这样的内容:
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */
我对注释“avoid getfield opcode”有点困惑......
这是什么意思? (我认为这避免了在字节码中使用getfield,但为什么这是一件好事[TM]?)
它是为了防止在trim不创建对象的情况下创建对象吗?不做任何事情(因此返回this)或者?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的猜测是,重点是将值复制到局部变量一次,以避免在接下来的几行循环的每次迭代中重复从堆中获取字段值。
当然,这就引出了一个问题:为什么相同的注释没有应用于“len”局部变量。 (我还希望 JIT 无论如何都能避免重新获取,尤其是当变量是最终变量时。)
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
用于获取类的成员变量。从剩余的代码中可以看出:
因此,当您处于循环中时,每次引用
value
或offset
时,它都必须执行getfield
>。如果循环运行很长时间,您可能会遭受很大的性能损失(因为每次测试循环条件时,都会针对offset
和 <代码>值)。因此,通过使用局部变量off
和val
可以减少性能损失。getfield
is used to get the member variable of a class.As you can see from the remaining code:
So when you're in a loop, it has to execute
getfield
every time you referencevalue
oroffset
. You can incur a large performance-hit if the loop runs for a long time (because every time the loop-condition is tested, agetfield
is exeuted for bothoffset
andvalue
). So by using the local variablesoff
andval
, you reduce the performance hit.