I have a doubt about the performance difference between these two things, get an object directly from a hashmap with the key vs get it from an Optional from an ArrayList. I will use these to save big amounts of data.
Note: the example below is only to show what I mean; I don't use static except in utils or specific things, I say this to prevent comments about static.
public class Main {
private static final List<User> users = Arrays.asList(new User(UUID.randomUUID()), new User(UUID.randomUUID()), new User(UUID.randomUUID()));
public static Optional<User> getUserByUUID(final UUID uuid){
return users.stream().filter(user -> user.getUuid().equals(uuid)).findFirst();
}
@RequiredArgsConstructor
@Getter@Setter
private static class User{
private final UUID uuid;
private int points;
private int gems;
}
}
vs
public class Main {
private static final Map<UUID, User> users = new HashMap<UUID, User>(){{
put(UUID.randomUUID(), new User());
put(UUID.randomUUID(), new User());
}};
public static User getUserByUUID(final UUID uuid){
if(users.containsKey(uuid))
return users.get(uuid);
return null;
}
@RequiredArgsConstructor
@Getter@Setter
private static class User{
private int points;
private int gems;
}
}
My point is, if one is better than the another one in terms of performance, is it insignificant?
Map#get will always be more performant than creating a Stream from a List and looking for a specific entry.
Map#get will give you a time complexity of O(1) basically
List#stream instead will give you a time complexity of O(n) plus extra space complexity: creation of a Stream and creation of an Optional
That said, if you have big amounts of data loaded in memory, this might lead to performance problems / OutOfMemoryErrors
It would be interesting to dig further in the problem and see if there isn't another way to handle this specific problem without loading big amounts of data directly in memory of the JVM
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With