0

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?

3
  • 1
    If you understood Java, you'd realize that it doesn't make any difference. If I create 100 objects on the heap, there's no difference between assigning their references to 100 individual fields or 100 array elements, except for the one extra reference for the array itself. Commented Jul 5, 2012 at 2:01
  • Can you give us an example with code? Commented Jul 5, 2012 at 2:35
  • If you can use shorter fields like short, char or byte this could save some memory. Commented Jul 5, 2012 at 6:54

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

If it had to order them, might it use a tiny bit more RAM storing the order of the List/Array?
Do you mean storing the elements in order? The different collection implementations are going to use different amounts of memory. But frankly, given how much memory the JVM will use when it gets up and running, the amount used by whatever collection implementation you use will be negligible.
Generally a List or Array is going to take more storage than a [] array -- maybe just another 16 bytes, or maybe twice as much, depending on the details.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.