Optimizing Code in Java
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
Understanding space complexity is crucial for building applications that:
OutOfMemoryError
Notation is identical to time complexity.
Some common complexity classes:
O(1)
: Constant time - size-independentO(n)
: Linear time - grows with input sizeO(n²)
: Quadratic time - grows quadratically with input sizepublic int findMax(int[] array) {
int max = Integer.MIN_VALUE;
for (int value : array) {
if (value > max) {
max = value;
}
}
return max;
}
Whether our array of integers has 10 elements or 10 million, we still only use memory for one single variable, max
The space complexity is O(1)
or constant space
public int[] doubleValues(int[] array) {
int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i] * 2;
}
return result;
}
n
elements, we need space for n
additional elementsO(n)
because the extra memory needed grows linearly with the input sizepublic int[][] multiplicationTable(int n) {
int[][] table = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
table[i][j] = (i + 1) * (j + 1);
}
}
return table;
}
n
is 10, we need 100 cells; if n
is 100, we need 10,000 cellsO(n²)
Memory is a finite resource!
Our previous examples in action, for an input size of 10,000 elements:
findMax
, O(1)
-> just a few extra bytesdoubleValues
, O(n)
-> around 40KB of extra memorymultiplicationTable
, O(n²)
-> around 400MB of extra memoryDon't forget:
Optimizing Code in Java