on the JVM, is there any performance penalty for u...
# server
j
on the JVM, is there any performance penalty for using UInt or UByte over Int and Byte?
s
No. The underlying representation is the same for both signed and unsigned types.
There might be a performance hit if the value ends up being represented as a boxed object instead of as a primitive, but that happens the same for both signed and unsigned types.
e
not equally, because the signed types have a built-in boxed instance cache and the unsigned ones don't
but the solution to that is to avoid boxing, whether you're using signed or unsigned types
👍 1
j
That cache is arguably a performance problem, not optimization, depending on what you're doing.
👍 1
j
I'm parsing byte streams, lots of them and converting 4 bytes or 8 bytes to Integers is something that happens thousands of times per request. Using unsigned types is just more convenient, especially where the value is known to be positive
k
Can you get the byte stream to come in as a ByteBuffer? If so, you can then call
buffer.asIntBuffer()
and you have a ready-made stream of ints.
j
oh wow, I didn't know about buffer.asIntBuffer! I'm already using a ByteBuffer, but some of the Ints are 2 bytes, some are 4 bytes, some are 8 bytes and then there are Strings inbetween as well and some Integers are signed while are others are unsigned, so I'll need to stick to bytes for this use-case
k
If you know the data type of the next set of bytes waiting to be read, you can just call
asIntBuffer()
or
asShortBuffer()
accordingly, read the next item, and the revert to reading it as bytes or whatever type is next.
e
ByteBuffer has getInt etc. methods, you don't need to use asIntBuffer to read ints out of it
j
buffer.getInt reads 4 bytes and I'm not sure if it's read in Big Endian or Little Endian; depending on the use-case, I need either one or the other. for other use-cases, I'll keep in mind that I can getShort to get a 2-byte Int, getInt for a 4-byte Int and getLong for a 8-byte Int, thanks for this!!
k
You can change the byte order on-the-fly between big and little endian, using the
order
method.
👍 1
e
like just about everything in Java, ByteOrder is big endian by default. as Klitos says, you can change the endianness on the fly.
👍 1