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 system समाधान:
public class UserRegistry {
private HashSet<String> users = new HashSet<>();
public boolean userExists(String username) {
return users.contains(username); // O(1) average time
}
}
HashMap: operations के लिए औसत समय जटिलता $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() method से हम 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 में कोड ऑप्टिमाइज़ करना