1

On many posts on Stackoverflow people said that using bytes or shorts instead of integers did not reduce the memory usage or CPU utilization. However, if I have an array of bytes or shorts, would that array use less memory and/or be faster to iterate over than a similar array of integers.

To be specific: I'm asking about the primitive type.

Joost Verbraeken
  • 883
  • 2
  • 15
  • 30
  • If you are asking about primitive types, [yes, it saves memory to use narrower types](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html). – Andy Turner Aug 28 '16 at 08:35
  • Sorry for the confusion, I meant bytes indeed. I changed the post. – Joost Verbraeken Aug 28 '16 at 08:36
  • @Defi If you need an `int[]` then you'll use one, if you need a `byte[]` it's only more complicated to use something else than a `byte[]`. What's the confusion here? – Kayaman Aug 28 '16 at 08:44
  • @Kayaman for **non-arrays** it makes (apparently) no sense to use bytes/shorts instead of integers and I was curious if that was also the case for **arrays** – Joost Verbraeken Aug 28 '16 at 08:56
  • 1
    If you use the most compact type for your problem, it will also be the smallest. If the array is large, this could be faster however, for a small array it might not make a difference. – Peter Lawrey Aug 28 '16 at 09:00
  • 1
    @Defi Even if it did make a difference for single variables, it would be micro-optimization. Unfortunately micro-optimization is most popular with people who don't really know how to program yet, but they're often needlessly worried about their program using 16 or 17 bytes of memory. With arrays you're usually dealing with larger amounts, so there is a chance that the memory savings are of some significance. Of course in some very, very special situations you will be interested in micro-optimization as well. – Kayaman Aug 28 '16 at 09:05

1 Answers1

1

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

As mentioned in Java documentation byte/short can be used for saving memory in large arrays.

In case of byte, the variable declared as byte can also serve as a form of a documentation since its value is limited by the range. ex of byte (-128 to 127).

Also take a look at the excellent answers in the following post,

In java, is it more efficient to use byte or short instead of int and float instead of double?

Community
  • 1
  • 1
Arthas
  • 145
  • 1
  • 12