Skip to content

Commit ad28e6c

Browse files
committed
Cached strings read from memory, reduces memory footprint heavily
1 parent ba2124e commit ad28e6c

2 files changed

Lines changed: 30 additions & 12 deletions

File tree

pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,11 @@
5050
<version>4.2.1</version>
5151
<scope>compile</scope>
5252
</dependency>
53+
<dependency>
54+
<groupId>net.openhft</groupId>
55+
<artifactId>zero-allocation-hashing</artifactId>
56+
<version>RELEASE</version>
57+
</dependency>
5358
</dependencies>
5459
<properties>
5560
<maven.compiler.source>1.8</maven.compiler.source>

src/main/java/com/beaudoin/jmm/misc/Strings.java

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,22 +24,35 @@
2424

2525
package com.beaudoin.jmm.misc;
2626

27+
import net.openhft.hashing.LongHashFunction;
28+
29+
import java.util.HashMap;
30+
import java.util.Map;
31+
2732
/**
2833
* Created by Jonathan on 12/21/2015.
2934
*/
3035
public final class Strings {
3136

32-
public static String transform(byte[] bytes) {
33-
for (int i = 0; i < bytes.length; i++) {
34-
if (bytes[i] == 0) {
35-
bytes[i] = 32;
36-
}
37-
}
38-
return new String(bytes).split(" ")[0].trim();
39-
}
40-
41-
public static String hex(int value) {
42-
return "0x" + Integer.toHexString(value).toUpperCase();
43-
}
37+
private static Map<Long, String> map = new HashMap<>(16_982);
38+
39+
public static String transform(byte[] bytes) {
40+
long hash = LongHashFunction.xx_r39().hashBytes(bytes);
41+
if (map.containsKey(hash)) {
42+
return map.get(hash);
43+
}
44+
for (int i = 0; i < bytes.length; i++) {
45+
if (bytes[i] == 0) {
46+
bytes[i] = 32;
47+
}
48+
}
49+
String string = new String(bytes).split(" ")[0].trim().intern();
50+
map.put(hash, string);
51+
return string;
52+
}
53+
54+
public static String hex(int value) {
55+
return "0x" + Integer.toHexString(value).toUpperCase();
56+
}
4457

4558
}

0 commit comments

Comments
 (0)