Ottimizzazione del codice in Java
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
Ora conosciamo la complessità in spazio e tempo!
Come applicarla per scrivere codice più efficiente?
Scegliendo la struttura dati giusta!
Stiamo creando un sistema di gestione utenti
Per un dato username, dobbiamo verificare se l'utente esiste
Usando una lista: complessità $O(n)$
public boolean usernameExists(ArrayList<String> users, String newUsername) {
for (String username : users) {
if (username.equals(newUsername)) {
return true;
}
}
return false;
}
Soluzione migliorata per la gestione utenti:
public class UserRegistry {
private HashSet<String> users = new HashSet<>();
public boolean userExists(String username) {
return users.contains(username); // O(1) average time
}
}
HashMap: $O(1)$ in media per le operazionipublic class UserCache {
private HashMap<String, UserProfile> userProfiles = new HashMap<>();
public UserProfile getUser(String username) {
return userProfiles.get(username); // O(1) average time
}
}
hashCode()ArrayList, non conoscevamo l'indice dell'username da trovarehashcode() convertiamo un oggetto in un indice cercabilepavlos.2020 -> 35189
HashMap e HashSet hanno un array sottostantehashCode() sull'elemento per ottenere un interoEsempio:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
"optimizingCodeInJava" -> 1406313774 // Implemented by Java
1406313774 % 16 = 14 <- questo è il nostro bucket!
LinkedList per il bucketScegliere la struttura dati giusta è come scegliere l'attrezzo giusto: un martello (ArrayList) va bene per i chiodi, ma è pessimo per le viti (meglio un Set).

Ottimizzazione del codice in Java