Using bytes, short and other primitive types

Why I do not see them quite often. I see them mainly for networks where size really matters. But, for example, I have a variable that uses only numbers from the range 1-10, should I use bytes? I use C / C ++ for encoding, using as little memory as possible, why is this not the case in java?

+6
source share
2 answers

In fact, on most processors that support Java, 32-bit integers are faster. For example, on Intel processors, 32-bit integer registers have the shortest operation codes, and 16-bit integers are processed a little slower. In addition, most of the time, using byte or short would not save you space.

It has nothing to do with OOPness; even in C, which really does not have any OOP concepts, int is often used for almost every number, since its size is often chosen so that it is the fastest width for a given architecture .

+10
source

If it is not as low as bit masking or memory intensity, where every byte of each object matters, I would probably use int , even if byte could do it.

Remember that Java objects are often complemented, making access to the JVM easier. therefore, depending on the other fields of your class, using a byte may still occupy the same memory as int! See javamex exploring Java memory usage

If I know that there are only 10 possible values, for OO reasons, I would not use byte to store it. Why will the values ​​be from 1 to 10? Does each meaning mean something special? If so, I would probably use enum and give each of these 10 values ​​a drop-down name for the intent.

+4
source

Source: https://habr.com/ru/post/984412/


All Articles