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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With