dnk
dnk

Reputation: 109

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:

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.

Upvotes: 3

Views: 193

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500515

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).

Upvotes: 6

Daniel Stradowski
Daniel Stradowski

Reputation: 3484

When you initialize an array, you reserve a place in memory for it. This memory size will not change depends on the values in the array. The default value in int array is 0, so your array is not partially empty.

Upvotes: 0

Related Questions