Zach Sugano
Zach Sugano

Reputation: 1607

Java what is more efficient memory wise?

I need to store a very large amount of instances of my class, and since I have a pretty terrible computer with only 2gb of RAM I need it to run with as little memory usage as possible. So can anyone tell me is it more efficient to have a ton of fields or an array. I don't care about the "best way" to do it, I need the way that uses the least RAM. So yeah, an array or many fields?

Upvotes: 0

Views: 192

Answers (2)

Hot Licks
Hot Licks

Reputation: 47699

Your question is a little unclear, but basically the class

public class SomeClass {
    int var1;
    int var2;
    ...
    int var100;
}

Will take as much space as an int[100] array. There might be a slight difference, depending on the platform, but no more than 16 bytes total, and it could go either way. (And you can substitute any other data type in place of int and the same thing will be true.)

But, just to be clear, either of the above takes up much less space than 100 objects, each containing one int.

Upvotes: 3

David B
David B

Reputation: 2698

An array doesn't condense the objects in any way, it just orders them. So fields or an array would have the same memory overhead.

That said, having an array of objects (or a List) would be better to keep your objects collected and together.

Upvotes: 2

Related Questions