2

Say if i want a array of 4 int's

ex.

int[] iA = {32,33,34,35};

would this array take up more memory than declaring them as individual Int's?

ex.

int i0 = 32;
int i1 = 33;
int i2 = 34;
int i3 = 35;
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Chikal Tretz
  • 131
  • 1
  • 7

3 Answers3

2

Each int is a primitive data type, whose sizes are defined in http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html.

The array is an object, which carries some overhead. There is a good discussion on how to find the size of Java objects in how calculate java array memory usage.

Community
  • 1
  • 1
Christian Garbin
  • 2,512
  • 1
  • 23
  • 31
  • Java does to my knowledge not specify how much memory a primitive use. And they might all be stored in at least 4bytes even when they would need only 2 or less. – zapl Jan 28 '14 at 03:08
  • Did you click on the link above, the one pointing to the Oracle site? – Christian Garbin Jan 28 '14 at 15:28
  • That are the sizes that you see in your program. That are not necessarily the sizes the JVM allocates to store them. 32bit / 64bit aligned memory is faster to access than using odd byte numbers - http://stackoverflow.com/questions/229886/size-of-a-byte-in-memory-java / similar thing: https://wikis.oracle.com/display/HotSpotInternals/CompressedOops – zapl Jan 28 '14 at 16:15
2

Space saving should not be the first concern influencing your decision here. You should think of answers to these questions:

  • Could the number of ints change in the future - if the answer is "yes", then you need an array.
  • Do you need "addressability" over your integers? - in other words, if you are given an index of, say, 3, do you need an ability to access i3? If the answer is "yes", you definitely need an array.

To answer your question, an array would take a few additional bytes of memory, because Java needs to allocate space to the array object itself. This overhead is noticeable when the number of ints is small, but it quickly goes down as your array grows.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Individual int will take less memory as there is

  1. Less array reference involved.
  2. No object padding involved

http://algs4.cs.princeton.edu/14analysis/

Rohit Sachan
  • 1,178
  • 1
  • 8
  • 16
  • You are making unwarranted assumptions. From the link that you posted: *"Moreover, the memory usage is typically padded to be a multiple of 8 bytes (on a 64-bit machine)."* – Stephen C Jan 28 '14 at 03:20