Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast conversion from one-dimensional array to two dimensional in Java

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?

like image 564
Yrlec Avatar asked Mar 17 '26 14:03

Yrlec


1 Answers

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.

like image 88
AlexR Avatar answered Mar 19 '26 03:03

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!