开发者

point of Byte and Short in Java (I've read the other questions)

开发者 https://www.devze.com 2023-02-24 09:42 出处:网络
My question is: If I got it right from the Java disassembly, when I use byte a=3,b=5; System.out.println(a+b);

My question is: If I got it right from the Java disassembly, when I use

byte a=3,b=5;
System.out.println(a+b);

would actually use int instead of byte. Also all local memory slots a开发者_开发知识库re 4B just as stack slots. I realize that allocating a byte array would probably act more efficiently, but is it true that using a single byte value is ultimately inefficient? (The same point for short)


+ is integer operation. that is why

byte c = a+b; // compile error

you should use

int c = a + b 

or

byte c = (byte)(a+b);

My advice is use int in order not to cast every time. If you always deal with byte use byte otherwise use int


It's important to realize that in Java the existence of byte and short are not primarily to have an integer data type with a smaller range. In almost all cases where (sufficiently small) numeric values are stored an int will be used, even if the valid range is just 0-100.

byte and short are used when some external factor restricts the data to be handled to those ranges. They simply exist to simplify interaction with such systems.

For example, file systems these days store byte streams. You could use int for all those reading/writing operations, but having a byte data type simplifies the operation and makes that distinction explicit.


The first rule of performance tuning should be to write simple, clear code.

In this example, there is no performance difference and even if there were the println() takes 10,000x times longer making any difference notional.


How a program appears in byte-code and how it appears in native code is different.

Not all slots are 4-bytes in the JVM. e.g. a reference on a 64-bit machine can be 8-bytes but it still uses one "slot"

Your machine doesn't have slots. It does have registers which are typically 32-bit or 64-bit.

In your example, byte operations are used, which are just as efficient as int operations, and can produce a different result so they are still required.

Note: an object with byte or short fields can be smaller than one with a int fields.

In this example, the JVM can calculate c once so it doesn't need a or b


Declare byte a=3,b=5; as final byte a=3,b=5; so that when this statement byte c = a+b; will get executed it will take byte not int.


Define inefficient.

Yes, the memory footprint might seem inefficient, but keep in mind most processors today are 32bit (or even 64bit). Storing a byte in only 8 bits would require the processor to get the 32 bits of address space and shift and clean it so the necessary 8 bits are in the right spot.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号