I have a class which I want to use some ten to 100 thousands of. Therefor I don't unnecessarily want to waste memory location for.
Only in a few (<100) of them I need 2 special variables. If I just declare them, but don't initialise them, do I need the same memory usage as if I would initialise them?
And if yes, do I have another option (besides making them an own class) to reduce memory usage?
This is my code example (name
and propability
I only need few times):
public class Neuron {
private String name;
private float propability;
private float connection[];
private float bias;
public Neuron(float[] connection, float bias) {
this.connection = connection;
this.bias = bias;
}
public Neuron(int propability, String name, float[] connection, float bias) {
this.name = name;
this.propability = propability;
this.connection = connection;
this.bias = bias;
}
//more code
}
I have to disagree a bit:
private float connection[];
private float bias;
The first one (the array) is a reference type. In other words: a (potential) pointer to some memory area. Obviously: as long as that pointer points to null
("nowhere"), no extra memory is required.
But make no mistake, your object itself needs to fit into memory. Meaning: when you instantiate a new Neuron
object, then the JVM requests exactly that amount of memory it needs to store a Neuron object. This means: there is a bit of memory allocated to fit that array reference into it, and of course: the memory for your float primitive values, they are all immediately allocated.
It doesn't matter whether you have 0 or 100.00 or 10394.283 stored in that member field: because the JVM made sure that you have enough memory to fit in the required bits and bytes.
Thus: when you really have millions of objects, each float field in your object adds 32 bits. No matter where the value within that field is coming from.
Sure, if your arrays will later hold 5 or 10 or 1000 entries, then that will make up most of your memory consumption. But initially, when you just create millions of "empty" Neuron
objects, you have to "pay" for each and any field that exists in your class.
Meaning: when only 1 out of 100 Neuron
object will ever need these two fields, then you could decide to have:
BaseNeuron
class that doesn't have all 4 fieldsAlso note that this can also be the better choice from a design perspective: "empty" values always mean: extra code to deal with that. Meaning: if that array can be null ... then of course, all code dealing with that field has to check whether the array is null before using it. Compare that to: a class not having that array, versus a class where you know that the array is always set and ready to use.
I am not saying that you absolutely must change your design, but as explained: you can reduce your memory footprint, and you could make your design more clear by doing so.