klikli-dev / modonomicon

Data-driven minecraft in-game documentation with progress visualization.
25 stars 9 forks source link

Use FastUtil instead of regular Java collections #206

Closed ByThePowerOfScience closed 4 months ago

ByThePowerOfScience commented 4 months ago

Fun fact:

/**
 * Constructs a new, empty set; the backing {@code HashMap} instance has
 * default initial capacity (16) and load factor (0.75).
 */
public HashSet() {
    map = new HashMap<>();
}

Java's HashSet actually uses an entire Hash Map to store its elements. It takes up over four times the space, and it's just... really awful. FastUtil's are significantly faster while using a quarter of the size. I used to use them all the time, but now it just makes me feel itchy whenever I see them used.

HashMaps on the other hand are also really unoptimized, using chaining (linked lists on the end of every value) to handle hash collisions instead of linear probing (finding a new spot for the next element to go into). This adds a lot of bloat, requiring Entry objects for every value, and is also significantly slower. It's not significant in terms of Big O - remaining in O(1) - but it's still an improvement. For such a foundational mod, every little bit helps.

Either way FastUtil is a completely drop-in replacement for standard Java collections, so it shouldn't cause any problems. I did avoid messing with any concurrent collections though, as FastUtil doesn't have a good answer for that currently.

klikli-dev commented 4 months ago

Thanks!