bluebox bluebox - 2 months ago 6
Vb.net Question

vb.net - Inserting 1-dimensional arrays into a 2-dimensional array

I'm working on an optimization algorithm and need to store some of the data (generated by the algorithm) in a 2-dimensional array called

matrix
, where row(i) contains the fitness score and parameter values of optimization vector(i).

Dim matrix(vectorCount() - 1, parameterCount()) As Double
Dim params(parameterCount() - 1) As Double

For i As Integer = 0 To vectorCount() - 1
matrix(i, 0) = vectorScore(i)
params = vectorValues(i)
For j As Integer = 0 To params.Length - 1
matrix(i, j+1) = params(j)
Next
Next


int
vectorCount()
returns the number of vectors.

int
parameterCount()
returns the number of parameters in each vector.

double
vectorScore(
int
vectorIndex)
returns the fitness score of a specified vector.

double[]
vectorValues(
int
vectorIndex)
returns the parameter values of a specified vector.

My question:

Is there a faster (i.e. more efficient) way to insert
params
into
matrix
?

Answer

If you want efficiency, relying on "plain" arrays is undoubtedly the best option. The reason why they are so efficient with respect to other alternatives (Collections, List, etc.) is because they contain the minimum amount of information required. If you want fancy functions allowing to sort the information easily/quickly or write complex queries to retrieve data, you shouldn't rely on arrays.

I always rely on a code like the one you wrote and haven't ever had a speed problem (this is really fast). I have done a quick research to make sure that there is no other option, but couldn't find any. The closest thing you have is Array.Copy, although it works just when the arrays have the same dimensions (I, personally, use it just with 1D arrays). In any case, I found an interesting link about Array.Copy() vs. loop performance for 2D arrays (it is in C# but everything is applicable to VB.NET).

Summary: your code is really fast and does not need to be improved. In case of having a valid alternative (Array.Copy working for 2D and 1D, what does not exist), the resulting performance would be just a bit better (and only for small array sizes).