Skip to content

Instantly share code, notes, and snippets.

@s-leroux
Created December 30, 2015 13:27
Show Gist options
  • Save s-leroux/1e6de2e505dd8b5c3dd6 to your computer and use it in GitHub Desktop.
Save s-leroux/1e6de2e505dd8b5c3dd6 to your computer and use it in GitHub Desktop.
Compare space used by three different options to store a matrix of 1000x1000 double values in Java
package demo;
import java.util.ArrayList;
public class OccupancyComparer {
static int S = 1000;
static double[][] array_of_double;
static Double[][] array_of_double_obj;
static ArrayList<Double> array_list_of_double_obj;
interface NullaryFunction {
void doIt();
}
public static void howMuchSpaceUsed(String useCase, NullaryFunction fct) {
Runtime rt = Runtime.getRuntime();
long usedMemBefore = rt.totalMemory() - rt.freeMemory();
fct.doIt();
long usedMB = (rt.totalMemory() - rt.freeMemory() - usedMemBefore) / 1024 / 1024;
System.err.println(useCase + " memory usage " + usedMB + " MB");
}
public static void main(String[] args) {
howMuchSpaceUsed("array_of_double", () -> {
array_of_double = new double[S][S];
});
howMuchSpaceUsed("array_of_double_obj", () -> {
array_of_double_obj = new Double[S][S];
for(int i = 0; i < S; ++i)
for(int j = 0; j < S; ++j)
array_of_double_obj[i][j] = new Double(0.0);
});
howMuchSpaceUsed("array_list_of_double_obj", () -> {
array_list_of_double_obj = new ArrayList<>(S*S);
for(int i = 0; i < S*S; ++i)
array_list_of_double_obj.add(new Double(0.0));
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment