การปรับแต่งโค้ดใน Java
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
ตอนนี้เรารู้จัก space และ time complexity แล้ว!
จะนำความรู้นี้ไปเขียนโค้ดที่มีประสิทธิภาพมากขึ้นได้อย่างไร?
ด้วยการเลือกโครงสร้างข้อมูลให้เหมาะสม!
กำลังสร้างระบบจัดการผู้ใช้งาน
ต้องการตรวจสอบว่า username ที่กำหนดนั้นมีอยู่ในระบบหรือไม่
ใช้ list: complexity $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: time complexity เฉลี่ย $O(1)$ สำหรับทุก operationpublic class UserCache {
private HashMap<String, UserProfile> userProfiles = new HashMap<>();
public UserProfile getUser(String username) {
return userProfiles.get(username); // O(1) average time
}
}
hashCode()ArrayList เราไม่รู้ index ของ username ที่ต้องการค้นหาhashcode() เราแปลง object ให้เป็น index ที่ใช้ค้นหาได้pavlos.2020 -> 35189
HashMap และ HashSet มี array เป็นโครงสร้างภายในhashCode() บน element เพื่อรับค่า integerตัวอย่าง:
[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 สำหรับ bucketการเลือกโครงสร้างข้อมูลเปรียบเหมือนการเลือกเครื่องมือให้เหมาะกับงาน - ค้อน (ArrayList) เหมาะกับตะปู แต่ไม่เหมาะกับสกรู (ซึ่ง Set อาจเป็นตัวเลือกที่ดีกว่า).

การปรับแต่งโค้ดใน Java