does array indexes affects performance/memory usage if they has no value

I'm new to Java and I've been wondering lately about memory consumption of huge, but partly empty array like in this case:

  • I need array of unknown size- it can be 300k of values, it can be 300m, but to keep in mind it might as well keep only like 50 values,
  • i'm initialising array with size of

    int values[] = new int[Integer.MAX_VALUE];
    
  • user generates some number of values that has to be stored in array every time given generating method is used

Is there any contraindication of using excessively huge arrays? How the size of array matters in case of performance when, say only 0,1% of that array is used vs 100% array usage?

In other words- when im calling empty array of X int values, will the JVM on initialisation reserve memory for X*(memory used to store 1 int value) even if there isn't any value stored yet?

Thanks, Daniel.

Jon Skeet
people
quotationmark

How the size of array matters in case of performance when, say only 0,1% of that array is used vs 100% array usage?

There's no such thing as an "empty array of X int values". Every element will have a value - it'll just be 0 by default. Every element will take 4 bytes, regardless of its value. Your new int[Integer.MAX_VALUE] array will take 8GB of memory.

If you want to create a sparse array, you might want to consider using a Map instead. However, note that while you can have an int array, a map would need an Integer type for the value - if you get outside the range of cached Integer values (and if you have a lot of different values) you could end up wasting a lot of space on Integer objects (and references to them).

people

See more on this question at Stackoverflow