r/java • u/davidalayachew • Dec 24 '25
When should we use short, byte, and the other "inferior" primitives?
After hearing Brian Goetz's "Growing the Java Language #JVMLS" as well as the recent post discussing the performance characteristics of short and friends, I'm starting to get confused.
I, like many, hold the (apparently mistaken) view that short is faster and takes less memory than int.
I now see how "faster" is wrong.
- It's all just machine level instructions -- one isn't inherently faster than the other.
- For reasons I'm not certain of, most machines (and thus, JVM bytecode, by extension) don't have machine level instructions for
shortand friends. So it might even be slower than that.
I also see how "less memory" is wrong.
- Due to the fact that the JVM just stores all values of
short,char, andbooleanas an extended version of themselves under the hood.
- Due to the fact that the JVM just stores all values of
So then what is the purpose of these smaller types? From what I am reading, the only real benefit I can find comes when you have an array of them.
But is that it? Are there really no other benefits of working with these smaller types?
And I ask because, Valhalla is going to make it easier for us to make these smaller value types. Now that my mistaken assumptions have been corrected, I'm having trouble seeing the value of them vs just making a value record wrapper around an int with the invariants I need applied in the constructor.
19
u/dadmda Dec 25 '25
I use byte a lot, but mostly in arrays because i use those to send and receive data through TCP and UDP sockets
9
u/DizzyInTheDark Dec 25 '25
In 26 years I’ve never used short. It’s the only primitive I’ve never used.
9
u/pron98 Dec 26 '25 edited Dec 26 '25
This is not true. Short and byte fields and array elements are represented differently from ints. Arrays of short and byte can significantly benefit not only from a smaller footprint, but, dependending on the access patterns and caching architecture of the CPU, from better performance.
But let me also repeat something I've said many times: A microbenchmark measures the performance of nothing but itself, and on the particualr machine it run on. The days when instructions had some deterministic cost and we could say that some instruction is cheap and another is expensive are long gone. The very same machine instruction running on the same machine can have a runtime cost that differs by as much as 100x depending on the state of the CPU at the time it runs, a state that depends on everything that's run before and on everything that's running concurrently. Add an optimising compiler on top of that, and the extrapolative power drops further. A microbenchmark measuring the performance of a method
foodoesn't actually measure the performance offoobut that of a program that consists of nothing butfoo. Havebarcallfooand the compiler might do something else.I'm not saying it's not possible to learn something about performance from a microbenchmark, but the only people who can learn anything are those who've designed whatever it is that is benchmarked, and understand what aspects are determined by the "ambient state" and what lessons can be extrapolated and under what conditions. Microbenchmarks have always been problematic, but since the rise of modern processors with multilevel caches, prefetch strategies, branch prediction employing machine learning 1, pipelines with speculative execution and instruction-level parallelism, deep-inlining JITs and so on, the only way to know anything significant about the performance of a particular program on a particular machine architecture is to profile that particular program on that particular machine architecture. Not to mention that both compilers and the nondeterministic CPU execution strategies also change from version to version.
6
u/Alex0589 Dec 25 '25 edited Dec 25 '25
Let's take Arrays.sort as an example when considering a large size array:
With AVX-512, you get:
So int[] gets 2× the parallelism of long[] per SIMD instruction. Now this won't make the sorting 2x faster because these operations are not all that's happening, but It does make a difference, as these benchmarks show: https://github.com/openjdk/jdk/pull/14227
Also consider that you wouldn't be able to use counting sort for Better performance if the short type didnt exist.
Now this Is where It gets interesting: the JVM has been able to perform auto vectorization for a long while. Let's Say you write a simple loop like this One:
for (int i = 0; i < arr.length; i++) { arr[i] = arr[i] * 2 + 1; }
When the JIT compiler warms up, this loop will get compiled and use SIMD instructions, assuming your CPU supports them. How many operations can be parellalized depends obviously on the instruction set your CPU supports(ex. AVX2 or AVX512), but also on the type of arr: a short is 2x smaller than an int, so 2x more operations can be parellalized if you switch from an int to a short arr in this case.
Things get super interesting now that we can use the Vector api to write our own vectorized operations. Take this project, which Is written in rust, but could now be implemented in Java as well without issues, and allows to decode a batch of scalar types as var ints: https://github.com/as-com/varint-simd
You can find a benchmark at the bottom of the page where different expected data types are compared(u8, u16, u32, u64 which are Just unsigned bytes, unsigned shorts, unsigned ints and unsigned longs, we don't consider negatives because negative var ints are Always the max length, that Is 10 bytes): look at how huge the performance difference Is.
Other things that come to my mind are object field packing, which can make a very big difference as the JVM Is free to reorder fields in a class for Better alignment but not to change their types and future proofing for valhalla.
4
u/two_three_five_eigth Dec 25 '25 edited Dec 25 '25
PSA - Chips have a register size (like 64 bit) every operation uses this chip. Compilers usually optimize for speed. Types are generally the size of the chip’s register.
Don’t try to outsmart the compiler.
4
u/_vertig0 Dec 27 '25
The only time those types are extended to int is on the evaluation stack. Inside arrays and objects, they very much take up less space than an int does. The evaluation stack also only exists within the Interpreter, when compiled by C1 and C2 it is completely eliminated, and the assembled code should very much be able to make use of byte and short.
Another interesting tidbit is that compiled bytecode will actually use the byte and short push to stack instructions if the constant is outside the range of the iconst instructions. Any bigger than a byte or short, and it'll have to go through the constant pool via ldc. ldc is much, much more heavyweight than bipush or sipush, so you could use byte or short to make sure you never go outside that range, I guess. As a result speed goes in the order of
ldc < sipush < bipush < iconst
sipush is implemented as follows in the Interpreter on x86 (All assembly snippets are not applicable when using the Zero Interpreter):
The bipush implementation is even shorter than sipush at just 1 instruction:
So you can see it very much does make a difference whether you use those shorter types or not.
2
u/davidalayachew Dec 27 '25
Thanks for the responses everyone. I didn't respond to everyone, but I definitely got my question answered. Here is the summary.
All in all though, the takeaway (so far -- still waiting on some people to respond to my responses) seems to be to model the semantics you need. If an object truly never will go past a certain point, use the "inferior" primitives!
For example, if I am modeling the location of pieces on a chess board, rather than making
record Point2D(int row, int column){}, I can definitely dorecord Point2D(byte row, byte column){}, since a chess board is an 8x8 grid! That's a good example of letting the semantics decide your data types. In fact, if I wanted to be really hacky, I could even use a single byte to model it.And of course, here is info straight from the Java tutorial itself -- Primitive Data Types, and when to use them. Lol, probably should have looked at this link first before making this post. It repeats a lot of what the comments here say.
2
u/k-mcm Dec 25 '25
The types are for binary compatibility, readability, and arrays.
If you need fast access to a dataset, smaller is faster. I wrote some software defined radios in Java and filter lookup table array size was an issue. There are distinct steps of performance corelating to which level of CPU cache everything fits into.
2
u/ryan_the_leach Dec 26 '25
Doing advent of code has led me to believe that I really should be using long more often then int as a default numeric type.
85
u/MattiDragon Dec 25 '25
byteis semanticly useful when you're doing IO or related things. In these areas arrays also tend to pop up as buffers.shortis rarely used, because signed 16bit values are rare in IO tasks and rarely have any use in application logic.charis used more often, although it should often be avoided due to its inability to represent all unicode codepoints.intis the recommended type for storing codepoints.14
u/Polygnom Dec 25 '25
Unless you are writing a binary protocol, crypto-related mechanics or a low-level string library, there is very little reason to ever touch short, byte or character.
26
u/sweetno Dec 25 '25 edited Dec 25 '25
shortis not faster indeed on x86-64, since the CPU designers rightfully wouldn't bother having a separate ALU for 16-bit arithmetic. But there are machine-level instructions for 16-bit types. They were inherited from Intel 16-bit processors for backward compatibility. Modern processors internally convert arguments to the full register width and then truncate the result, so it's slower.However,
shortdoes take less memory thanint. This is visible not only with arrays, but also with class members: instances ofclass A { short x; short y; }take less memory than ofclass B { int x; int y; }. That can make a big difference if you, say, have arrays of those objects.It's when you declare a small type variable on stack will it be padded with extra memory for faster access.
Valhalla doesn't have to do much with the small types per se, it's about reducing JVM memory usage by adding C#
structs andArrayList<int>functionality. No idea why it takes them so many years.In practice, just use
intunless you have a practical reason to do otherwise.12
u/redikarus99 Dec 25 '25
One reason might be to use short to represent elements in a binary protocol.
1
u/D4rklordmaster Dec 26 '25
Edit: ok i am stupid and didnt see u linked my post 😭
i recently made a very misinformed post due to my lack experience regarding speed of int vs byte vs short etc. And it got alot of comments, many of which actually answers your question. give the comments a view and ull get the gist of it.
https://www.reddit.com/r/java/comments/1ptxcsk/long_is_faster_than_int_short_and_byte_are_not/
tldr shorts and bytes have their place in arrays, they dont really exist outside of that in normal operations (take with grain of salt my experience is low)
1
u/Roast3000 Dec 25 '25
I am not really sure if this is right, but aren‘t primitives more likely to be stored on the stack, whereas object types are stored on the heap ?