Even if not used in the constructor :
public Neuron(float[] connection, float bias) {
this.connection = connection;
this.bias = bias;
}
all instance fields (so name
and propability
too) are initialized before that the constructor be executed.
These are initialized with a default value :
private String name; // null
private float propability; // 0F
But these default values cost nothing (null
and 0
).
So don't bother with that.
I have a Class which I want to use some ten to 100 thousands of.
Therefor I don't unnecessarily wanna waste memory location for.
And if yes, do I have another option (besides making them an own
class) to reduce memory usage?
If these objects have some common data, share these data between the instances.
The flightweight pattern that rely on immutability of shared data illustrates that practice.
The String
objects use that.
Agreed completely with the remark of GhostCat : fields even not used consume memory. Not a lot but they consume. But that is right for many classes in Java.
For example we will not replace all lists by arrays because the arrays consume less in general. We will do that because in our specific case, the list memory occupation is a real worry.
To sum up, before optimizing and to change our design, I think that the first thing to do is measuring and to deem whether you want to optimize to gain gold or nuts.
With your actual code and that main()
method that produces 1 millions of Neuron, I notice that about 131 Mo
are consumed :
public static void main(String[] args) {
long beforeUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
List<Neuron> neurons = new ArrayList<>();
for (int i = 0; i < 1_000_000; i++) {
neurons.add(new Neuron(new float[] { 0, 15.4F, 1.1F, 2.1F, 3.4F, 4.5F, 8.9F, 158.9F, 8648.9F, 80.9F, 10.9F, 1450.9F, 114.9F, 14.5F, 4444.4F }, 1.9F));
}
long afterUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
long actualMemUsed=(afterUsedMem-beforeUsedMem)/1_000_000;
System.out.println(actualMemUsed + " Mo");
}
Objectively, it is low.
By removing the unused fields, it drops about to 124 Mo
(7 Mo in less) :
private String name;
private float propability;
131 Mo as 124 Mo are quite low values for so many created objects : 1 million.
If the class declared a dozen of unused fields, things would be different. A no negligible amount of memory would be wasted and overall the class would be not clear at all in terms of design : low cohesion.
But there that is not the case.