Let's say I have a method with the following signature:
public int indexOf(byte[] bytes, byte toFind, int offset, int length) {
...
}
This method does something simple like look for the byte toFind
in the range [offset, offset+length) in bytes
. I want to check up-front whether offset and length are valid for bytes
. That is, that offset and offset + length fall in bytes.
The explicit check would look something like:
if (offset < 0 || offset > bytes.length - length) {
throw ...; // bad santa!
}
It seems that I can perform this more cheaply (in terms of emitted bytecode, and perhaps runtime performance) by performing "dummy" array access instead:
public int indexOf(byte[] bytes, byte toFind, int offset, int length) {
int dummy = bytes[offset] + bytes[offset + length - 1];
...
}
I'd like to get rid of the int dummy
and +
if I could, or reduce their cost. The compiler doesn't like standalone accesses like bytes[offset];
, presumably because an expression like this usually doesn't have side effects and is pointless (but not so in this case). Using the dummy int also causes a compiler warning which must be suppressed.
Any suggestions on how I can make the change with a minimum amount of bytecode (runtime performance is important here too, but I suspect that most solutions are optimized to the same thing as unused portions are dropped).