Skip to content

Commit 763c153

Browse files
author
Tyler
authored
Faster hashCode using the Effective Java method. (#14)
Caching the hashCode value in the object is a slow-down in my tests.
1 parent c9a1e5d commit 763c153

File tree

2 files changed

+15
-11
lines changed

2 files changed

+15
-11
lines changed

src/main/java/com/javadocmd/simplelatlng/LatLng.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,8 +185,10 @@ public boolean equals(Object obj) {
185185

186186
@Override
187187
public int hashCode() {
188-
String s = Long.toString(latitude) + "|" + Long.toString(longitude);
189-
return s.hashCode();
188+
int result = 1;
189+
result = 31 * result + (int) (latitude ^ (latitude >>> 32));
190+
result = 31 * result + (int) (longitude ^ (longitude >>> 32));
191+
return result;
190192
}
191193

192194
@Override

src/test/java/com/javadocmd/simplelatlng/SpeedProfile.java

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,10 @@
1919
import java.text.NumberFormat;
2020
import java.util.Date;
2121

22-
import com.javadocmd.simplelatlng.Geohasher;
23-
import com.javadocmd.simplelatlng.LatLng;
24-
import com.javadocmd.simplelatlng.LatLngTool;
2522
import com.javadocmd.simplelatlng.util.LengthUnit;
2623
import com.javadocmd.simplelatlng.window.CircularWindow;
2724
import com.javadocmd.simplelatlng.window.RectangularWindow;
2825

29-
3026
/**
3127
* Basic benchmarking test. Repeats the critical functions
3228
* a bunch of times and reports how long that took. Also
@@ -51,6 +47,7 @@ public static void main(String[] args) {
5147
p.profileRectangularWindow();
5248
p.profileCircularWindow();
5349
p.profileGeohasher();
50+
p.profileHashCode();
5451
}
5552

5653
private LatLng[] points;
@@ -108,14 +105,19 @@ private void profileGeohasher() {
108105

109106
System.out.printf("Geohashed and decoded in %s ms.\n", integer.format(end.getTime()
110107
- start.getTime()));
108+
}
111109

112-
start = new Date();
113-
for (int i = 0; i < points.length; i++) {
114-
points[i].hashCode();
110+
private void profileHashCode() {
111+
// Repeat 5 times in hopes of detecting a caching benefit if any exists.
112+
Date start = new Date();
113+
for (int j = 0; j < 5; j++) {
114+
for (int i = 0; i < points.length; i++) {
115+
points[i].hashCode();
116+
}
115117
}
116-
end = new Date();
118+
Date end = new Date();
117119

118-
System.out.printf("hashCode() in %s ms.\n", integer.format(end.getTime()
120+
System.out.printf("hashCode() 5x in %s ms.\n", integer.format(end.getTime()
119121
- start.getTime()));
120122
}
121123

0 commit comments

Comments
 (0)