The JVM documentation states that short is implemented as an int, so I am wondering if there can be any upside to using it instead. Does it maybe use less memory or process faster?
-
3The documentation you read is correct. There's simply no point if you're not storing it in an array. – Louis Wasserman Nov 04 '15 at 18:31
2 Answers
This is just an opinion but I would say it's not wise.
- You deviate from the standard everybody knows. People suddenly need to think about the correctness and intention of your for loops. This wastes precious development time which is maybe even more expensive than a few bytes of memory.
- It will also introduce subtle bugs when at some point someone changes from 100 to a larger value: the compiler does not complain, yet you may be creating an infinite loop.
For example
for (short s = 0; s < Short.MAX_VALUE + 1; s++)
never stops because s++
overflows silently, while s
in s < Short.MAX_VALUE + 1
is promoted to int
.
Using types smaller than int
is best reserved for times when you want the semantic of a 2 byte value & how it overflows, not in an attempt to save space.

- 63,179
- 10
- 123
- 154
There's not really an upside to it, see this anwer to a similar question:
https://stackoverflow.com/a/14532302/5490728
It even talks about possible loss of performance.
Also, as zapl already pointed out, collaborators might not be used to it and produce bugs out of it.
(I read it should be possible to mark this question as duplicate with 15 reputation, but I can't find the option in the 'flag' menu. I hope this way of answering is ok, too.)

- 1
- 1

- 38
- 7