Reputation: 3458
I need to convert a long[] to long[][] as quickly as possible in Java. The long[] might not fully correspond to the long[] and in that case I append empty rows to the long[].
The current code looks like this:
private long[][] convertOneDimensionalToTwoDimensional(int numberOfRows, int rowSize, long[] srcMatrix) {
int srcMatrixLength = srcMatrix.length;
int srcPosition = 0;
long[][] returnMatrix = new long[numberOfRows][];
for (int i = 0; i < numberOfRows; i++) {
long[] row = new long[rowSize];
int nextSrcPosition = srcPosition + rowSize;
if (srcMatrixLength >= nextSrcPosition) {
// Copy the data from the file if it has been written before. Otherwise we just keep row empty.
System.arraycopy(srcMatrix, srcPosition, row, 0, rowSize);
}
returnMatrix[i] = row;
srcPosition = nextSrcPosition;
}
return returnMatrix;
}
Any ideas on how to make this more efficient? For instance, is there any way to avoid the memory copy?
Upvotes: 3
Views: 3654
Reputation: 115328
I think that you have implemented the fastest solution since you are using System.arraycopy()
. This is the fastest solution until you are using arrays.
But if performance is a real issue here and you can switch from arrays to collections or lists you can do better implementation. You can implement your own collection that uses one dimensional array and behaves as 2 dimensional collection.
Upvotes: 3