Java 代码优化
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
我们已了解空间与时间复杂度!
如何运用它来写更高效的代码?
选择合适的数据结构!
我们在构建用户管理系统
需要检查给定用户名的用户是否存在
使用列表:复杂度为 $O(n)$
public boolean usernameExists(ArrayList<String> users, String newUsername) {
for (String username : users) {
if (username.equals(newUsername)) {
return true;
}
}
return false;
}
改进的用户管理方案:
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)$public class UserCache {
private HashMap<String, UserProfile> userProfiles = new HashMap<>();
public UserProfile getUser(String username) {
return userProfiles.get(username); // O(1) average time
}
}
hashCode()ArrayList 示例中,我们不知道要找的用户名的索引hashcode() 方法,可将对象转换为可定位的索引pavlos.2020 -> 35189
HashMap 和 HashSet 底层是数组hashCode() 得到整数示例:
[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选择数据结构就像为任务选对工具——锤子(ArrayList)适合钉子,但拧螺丝时也许用 Set 更好。

Java 代码优化