I need to store a 2d matrix containing zip codes and the distance in km between each one of them. My client has an application that calculates the distances which are then s
Lately I've managed similar requisites for my master thesis.
I ended with a Matrix class that uses a double[]
, not a double[][]
, in order to alleviate double deref costs (data[i]
that is an array, then array[i][j]
that is a double
) while allowing the VM to allocate a big, contiguous chunk of memory:
public class Matrix {
private final double data[];
private final int rows;
private final int columns;
public Matrix(int rows, int columns, double[][] initializer) {
this.rows = rows;
this.columns = columns;
this.data = new double[rows * columns];
int k = 0;
for (int i = 0; i < initializer.length; i++) {
System.arraycopy(initializer[i], 0, data, k, initializer[i].length);
k += initializer[i].length;
}
}
public Matrix set(int i, int j, double value) {
data[j + i * columns] = value;
return this;
}
public double get(int i, int j) {
return data[j + i * columns];
}
}
this class should use less memory than an HashMap
since it uses a primitive array (no boxing needed): it needs only 906304 * 8 ~ 8 Mb
(for doubles) or 906304 * 4 ~ 4 Mb
(for floats). My 2 cents.
NB I've omitted some sanity checks for simplicity's sake