I wasn't sure exactly how to word this question, but basically, I have a struct stNeuralLayers
(for a neural network I'm playing around with) with fields that are matrices (such as a double[,] neuralWeights
field and a double[,] results
field), and I have a field that's an array of those structs (stNeuralLayers[] fldNeuralLayers
).
The way I originally wrote it was that I had separate fields in the class (not in the struct) that were maintained separately such as int[] fldWeightsPerNeuron
(which would store the number of weights per neuron for each layer as an array for the corresponding field) with the corresponding read-only property int[] numWeightsPerNeuron
which would return a clone of the field.
The reason for this is because in a lot of places, I'm looping through the weights and accessing fldWeightsPerNeuron[i]
in a statement like for (int j = 0; j < fldWeightPerNeuron[i]; j++)
is I think faster, especially if your also looping through all the layers with for (int i = 0; i < numLayers; i++)
(numLayers
is also an int
field that's maintained separately).
Obviously, the cost of this is the code required to maintain those fields when anything is updated, so I through around the idea of just getting rid of the fields and creating read-only properties that just fetch the needed data directly (such as putting public int weightsPerNeuron { get { return weights.GetLength(1); } }
directly in the struct itself). The cost of doing that I think is if I use those properties directly in those for loop statements, it'l slow down performance (since accessing the GetLength() method each time is slower than accessing a single element of an array each time). I could also create temporary variables to store that data (such as int[] weightsPersNeuron = fldNeuralLayers.Select(x => x.weights.GetLength(1)).ToArray();
within the method for each method that would need it, but that's really just replacing one set of code (the code for maintaining separate fields) with another set of code (the code for declaring those variables and creating the arrays to assign to them within the various methods).
Is there a best practice for this?