Skip to content

Commit 629cedd

Browse files
authored
Optimize Vec3i hashing (#573)
1 parent 1a183d4 commit 629cedd

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
2+
From: HaHaWTH <[email protected]>
3+
Date: Tue, 9 Nov 2077 00:00:00 +0800
4+
Subject: [PATCH] Optimize Vec3i hashing
5+
6+
Replaces the default hashCode calculation with a high-quality spatial hasher.
7+
This implementation utilizes large prime coefficients and Phi mixing (for avalanche effect) to significantly reduce hash collisions,
8+
thereby improving lookup performance and mitigating worst-case hash distribution scenarios.
9+
10+
diff --git a/net/minecraft/core/Vec3i.java b/net/minecraft/core/Vec3i.java
11+
index 8334e92013722bf2fc7b4c26e38f7ca1e75b6191..886da8b99e344eb352405de421aa77fe2c73b22b 100644
12+
--- a/net/minecraft/core/Vec3i.java
13+
+++ b/net/minecraft/core/Vec3i.java
14+
@@ -47,7 +47,7 @@ public class Vec3i implements Comparable<Vec3i> {
15+
16+
@Override
17+
public final int hashCode() { // Paper - Perf: Final for inline
18+
- return (this.getY() + this.getZ() * 31) * 31 + this.getX();
19+
+ return org.dreeam.leaf.util.Vec3iHasher.hash(this.x, this.y, this.z); // Leaf - Optimize Vec3i hashing
20+
}
21+
22+
@Override
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package org.dreeam.leaf.util;
2+
3+
/**
4+
* A high-quality 3D coordinate hasher that prioritizes distribution over raw instruction count.
5+
* <p>
6+
* This implementation trades a marginal amount of calculation speed for extremely low hash collision rates,
7+
* significantly improving the performance of large HashMaps.
8+
*/
9+
public final class Vec3iHasher {
10+
11+
// See https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm
12+
// 2^32 * (sqrt(5) - 1) / 2
13+
private static final int INT_PHI = 0x9E3779B9;
14+
15+
private Vec3iHasher() {
16+
}
17+
18+
public static int hash(int x, int y, int z) {
19+
final int h = x * 31337 + y * 961 + z;
20+
21+
final int hash = h * INT_PHI;
22+
return hash ^ (hash >>> 16);
23+
}
24+
}

0 commit comments

Comments
 (0)