Code optimaliseren in Java
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
Wiskundige notatie voor het worstcasescenario.
Veelvoorkomende complexiteitsklassen:
O(1): Constante tijd - onafhankelijk van grootteArrayList's get()Interne (vereenvoudigde) implementatie voor een ArrayList met 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)
}
}
Wiskundige notatie voor het worstcasescenario
Veelvoorkomende complexiteitsklassen:
O(1): Constante tijd - onafhankelijk van grootteO(n): Lineaire tijd - groeit met invoergrootteArrayList'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
}
Wiskundige notatie voor het worstcasescenario
Veelvoorkomende complexiteitsklassen:
O(1): Constante tijd - onafhankelijk van grootteO(n): Lineaire tijd - groeit met invoergrootteO(n²): Kwadratische tijd - groeit kwadratisch met invoer// 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!")
}
}
}
}
Effect van invoergrootte:
O(1): 1.000 -> 1.000.000 items = Zelfde tijd!O(n): 1.000 -> 1.000.000 items = 1.000× tragerO(n²): 1.000 -> 1.000.000 items = 1.000.000× trager
Code optimaliseren in Java