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.

+1


source to share


4 answers


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.

+6


source


Since all integer types in java are signed, you still have to mask the 8 bits of the b value if you expect to read from file values ​​greater than 0x7F:



byte b;
byte a[256];
a [b & 0xFF] = x;

      

+2


source


Not; array indices are non-negative integers (JLS 10.4) , but byte indices will be supported.

0


source


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.

0


source







All Articles