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

此生再无相见时 提交于 2019-12-12 21:26:46

问题


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 are 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)


回答1:


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




回答2:


+ 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




回答3:


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.




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/5662685/point-of-byte-and-short-in-java-ive-read-the-other-questions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!