Optimizing Code in Java
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
Mathematical notation to describe worst-case scenario.
Some common complexity classes:
O(1)
: Constant time - size-independentArrayList
's get()
Internal (simplified) implementation for an ArrayList
that holds Strings
:
public class ArrayList {}
private String[] data; // Internal array
private int size;
// Get operation - direct array access
public String get(int index) {
return data[index]; // O(1)
}
}
Mathematical notation to describe worst-case scenario
Some common complexity classes:
O(1)
: Constant time - size-independentO(n)
: Linear time - grows with input sizeArrayList
's contains()
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
// Linear search through array
for (int i = 0; i < size; i++) {
if (o.equals(elementData[i])) {
return i;
}
}
return -1; // Not found
}
Mathematical notation to describe worst-case scenario
Some common complexity classes:
O(1)
: Constant time - size-independentO(n)
: Linear time - grows with input sizeO(n²)
: Quadratic time - grows quadratically with input size// Finding a pair of numbers that sum to a target value
// Time complexity: O(n²)
public int[] findPairWithSum(ArrayList<Integer> numbers, int targetSum) {
for (int i = 0; i < numbers.size(); i++) {
for (int j = i + 1; j < numbers.size(); j++) {
if (numbers.get(i) + numbers.get(j) == targetSum) {
console.log("Found them!")
}
}
}
}
Input size impact:
O(1)
: 1,000 -> 1,000,000 items = Same time!O(n)
: 1,000 -> 1,000,000 items = 1,000× slowerO(n²)
: 1,000 -> 1,000,000 items = 1,000,000× slowerOptimizing Code in Java