Java - indexing into array with byte
Is it possible to index a Java array based on a byte?
i.e. something like
array[byte b] = x;
I have a very performance critical application that reads b (in the code above) from a file, and I don't want the overhead of converting that to int. What is the best way to achieve this? Is there a performance hit as a result of using this indexing method and not int?
With great thanks,
Froskoy.
source to share
There is no overhead for "converting this to int". At the Java bytecode level, everything is byte
already int
s.
In any case, if the array indexing will be automatically promoted to int
. None of these features will improve performance, and many will decrease performance. Just leave your code using int
.
JVM Specification Section 2.11.1 :
Note that most of the instructions in Table 2.2 do not have integral type byte forms, char and short. Nobody has a form for a boolean type. Compilers encode many literal values ββof bytes of types and abbreviate them using Java virtual machine instructions that sign these values ββto int values ββat compile time or run time. Loading literal values ββof types boolean and char is encoded using instructions that null-expand the literal to an int value at compile time or run time. Likewise, loads from arrays of boolean, byte, short, and char values ββare encoded using Java virtual machine instructions that expand or round values ββto int values. Thus, most operations on values ββof actual types boolean, byte,char and short are executed correctly by instructions using values ββof computational type int.
source to share
Not; array indices are non-negative integers (JLS 10.4) , but byte indices will be supported.
source to share
No, there is no performance penalty, because the moment you read a byte, you store it in the CPU register . These registers always work with WORDs , which means that a byte is always "converted" to int (or long if you're 64 bit).
So, just read your byte like this:
int b = (in.readByte() & 0xFF);
If your application is performance critical, you should optimize it elsewhere.
source to share