Skip to content

Commit 045cc78

Browse files
authored
Merge pull request #1 from Grabsky/fix/prevent-class-lookups
fix: prevent redundant class lookups
2 parents fed3d1f + b76a3f4 commit 045cc78

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

luajava/src/main/java/party/iroiro/luajava/JuaAPI.java

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,30 @@
4040
* </p>
4141
*/
4242
public abstract class JuaAPI {
43+
44+
private static final short UNRESOLVED_CACHE_SIZE = 10_000;
45+
46+
// Holds a set of class names that failed to be resolved
47+
private static final LinkedHashSet<String> UNRESOLVED = new LinkedHashSet<String>(UNRESOLVED_CACHE_SIZE) {
48+
49+
@Override
50+
public boolean add(final String obj) {
51+
// Returning early if element is already in the set.
52+
if (this.contains(obj) == true)
53+
return false;
54+
// Removing first entry if set has reached it's size.
55+
if (this.size() >= UNRESOLVED_CACHE_SIZE) {
56+
final Iterator<String> iterator = this.iterator();
57+
if (iterator.hasNext() == true) {
58+
iterator.next();
59+
iterator.remove();
60+
}
61+
}
62+
return super.add(obj);
63+
}
64+
65+
};
66+
4367
/**
4468
* Allocates a direct buffer whose memory is managed by Java
4569
*
@@ -471,10 +495,15 @@ public static int classIndex(int index, Class<?> clazz, String name) {
471495
if (i == 1) {
472496
return 1;
473497
} else {
498+
final String className = clazz.getName() + "$" + name;
499+
// Preventing redundant (and expensive) lookups if already marked as unresolved
500+
if (UNRESOLVED.contains(className) == true)
501+
return i;
474502
try {
475-
L.pushJavaClass(ClassUtils.forName(clazz.getName() + '$' + name));
503+
L.pushJavaClass(ClassUtils.forName(className));
476504
return 1;
477505
} catch (ClassNotFoundException e) {
506+
UNRESOLVED.add(className); // Marking as unresolved
478507
return i;
479508
}
480509
}

0 commit comments

Comments
 (0)