Java में कोड ऑप्टिमाइज़ करना
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
अब हमें space और time complexity पता है!
इसे इस्तेमाल कर बेहतर, कुशल कोड कैसे लिखें?
सही data structure चुनकर!
हम एक user management system बना रहे हैं
दिए गए username के लिए जाँचना है कि user मौजूद है या नहीं
List का उपयोग: complexity $O(n)$
public boolean usernameExists(ArrayList<String> users, String newUsername) {
for (String username : users) {
if (username.equals(newUsername)) {
return true;
}
}
return false;
}
बेहतर user management समाधान:
public class UserRegistry {
private HashSet<String> users = new HashSet<>();
public boolean userExists(String username) {
return users.contains(username); // O(1) average time
}
}
HashMap: operations के लिए औसत time complexity $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 उदाहरण में, हमें username का index पता नहीं थाhashcode() से हम object को ऐसे index में बदलते हैं जिसे देखा जा सकेpavlos.2020 -> 35189
HashMap और HashSet के नीचे एक array होता हैhashCode() कॉल कर एक 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 <- यही हमारा bucket है!
LinkedListData structure चुनना काम के लिए सही औज़ार चुनने जैसा है - हथौड़ा (ArrayList) कील के लिए बढ़िया है, पर स्क्रू के लिए खराब है (जहाँ Set बेहतर होगा)।

Java में कोड ऑप्टिमाइज़ करना