Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding getfield opcode

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?

like image 868
SyntaxT3rr0r Avatar asked Jan 21 '11 17:01

SyntaxT3rr0r


2 Answers

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

like image 81
Jon Skeet Avatar answered Oct 06 '22 19:10

Jon Skeet


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.

like image 35
Vivin Paliath Avatar answered Oct 06 '22 18:10

Vivin Paliath