Optimizing Code in Java
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
We now know about space and time complexity!
How do we apply this understanding to write more efficient code?
By choosing the right data structure!
We are building a user management system
We need to check, for a given username, if a user exists
Using a list: complexity $O(n)$
public boolean usernameExists(ArrayList<String> users, String newUsername) {
for (String username : users) {
if (username.equals(newUsername)) {
return true;
}
}
return false;
}
Improved user management system solution:
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)$ average time complexity for operationspublic class UserCache {
private HashMap<String, UserProfile> userProfiles = new HashMap<>();
public UserProfile getUser(String username) {
return userProfiles.get(username); // O(1) average time
}
}
hashCode()
ArrayList
example, we did not know the index of the username to findhashcode()
method, we can convert an object into a index we can look forpavlos.2020 -> 35189
HashMap
and HashSet
have an underlying arrayhashCode()
on your element to get an integerExample:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
"optimizingCodeInJava" -> 1406313774 // Implemented by Java
1406313774 % 16 = 14 <- that's our bucket!
LinkedList
for the bucketData structure selection is like choosing the right tool for a job - a hammer (ArrayList
) is great for nails but terrible for screws (where a Set
might work better).
Optimizing Code in Java