Add string cache to pool most commonly used Java strings
This commit is contained in:
@@ -25,8 +25,8 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.ref.WeakReference;
|
||||
|
||||
import org.luaj.vm2.lib.MathLib;
|
||||
import org.luaj.vm2.lib.StringLib;
|
||||
|
||||
public class LuaString extends LuaValue {
|
||||
@@ -37,11 +37,36 @@ public class LuaString extends LuaValue {
|
||||
public final int m_offset;
|
||||
public final int m_length;
|
||||
|
||||
private static final int STRINGCACHE_POW2 = 10;
|
||||
private static final WeakReference[] stringcache
|
||||
= new WeakReference[1<<STRINGCACHE_POW2];
|
||||
|
||||
private static class LuaJavaString extends LuaString {
|
||||
private final String string;
|
||||
private LuaJavaString(String value, byte[] bytes) {
|
||||
super(bytes);
|
||||
string = value.intern();
|
||||
}
|
||||
public String toString() {
|
||||
return string;
|
||||
}
|
||||
}
|
||||
|
||||
public static LuaString valueOf(String string) {
|
||||
int h = string.hashCode();
|
||||
int i = h & ((1<<STRINGCACHE_POW2)-1);
|
||||
if ( stringcache[i] != null ) {
|
||||
LuaJavaString s = (LuaJavaString) stringcache[i].get();
|
||||
if ( s != null && s.string == string ) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
char[] c = string.toCharArray();
|
||||
byte[] b = new byte[lengthAsUtf8(c)];
|
||||
encodeToUtf8(c, b, 0);
|
||||
return new LuaString(b);
|
||||
LuaJavaString s = new LuaJavaString(string,b);
|
||||
stringcache[i] = new WeakReference(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
public LuaString(byte[] bytes, int offset, int length) {
|
||||
|
||||
@@ -127,7 +127,7 @@ public class UnaryBinaryOperatorsTest extends TestCase {
|
||||
|
||||
// objects should be different
|
||||
assertNotSame(ia, ib);
|
||||
assertNotSame(sa, sb);
|
||||
assertSame(sa, sb);
|
||||
assertNotSame(ia, ic);
|
||||
assertNotSame(sa, sc);
|
||||
|
||||
@@ -148,7 +148,7 @@ public class UnaryBinaryOperatorsTest extends TestCase {
|
||||
|
||||
// objects should be different
|
||||
assertNotSame(da, db);
|
||||
assertNotSame(sa, sb);
|
||||
assertSame(sa, sb);
|
||||
assertNotSame(da, dc);
|
||||
assertNotSame(sa, sc);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user