Skip to content

Instantly share code, notes, and snippets.

@headius
Created March 2, 2023 18:12
Show Gist options
  • Save headius/5700bac0fca84999769ec4b7ef5e3a05 to your computer and use it in GitHub Desktop.
Save headius/5700bac0fca84999769ec4b7ef5e3a05 to your computer and use it in GitHub Desktop.
diff --git a/core/src/main/java/org/jruby/parser/StaticScope.java b/core/src/main/java/org/jruby/parser/StaticScope.java
index 66c9b71c61..32c644f730 100644
--- a/core/src/main/java/org/jruby/parser/StaticScope.java
+++ b/core/src/main/java/org/jruby/parser/StaticScope.java
@@ -37,6 +37,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
+import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.IntFunction;
@@ -93,6 +94,10 @@ public class StaticScope implements Serializable {
// as key to Symbol table for actual encoded versions].
private String[] variableNames;
+ // A set containing all known variable names, to quickly check for existing definitions.
+ // This is only used at parse/construction time.
+ private Map<String, Integer> knownVariables;
+
private int variableNamesLength;
// Arity of this scope if there is one
@@ -365,10 +370,11 @@ public class StaticScope implements Serializable {
}
private int findVariableName(String name) {
- for (int i = 0; i < variableNames.length; i++) {
- if (name.equals(variableNames[i])) return i;
+ Integer index;
+ if (knownVariables == null || (index = knownVariables.get(name)) == null) {
+ return -1;
}
- return -1;
+ return index;
}
/**
@@ -635,7 +641,10 @@ public class StaticScope implements Serializable {
System.arraycopy(variableNames, 0, newVariableNames, 0, variableNames.length);
variableNames = newVariableNames;
variableNamesLength = newVariableNames.length;
- variableNames[variableNames.length - 1] = name;
+ int newIndex = variableNames.length - 1;
+ variableNames[newIndex] = name;
+ if (knownVariables == null) knownVariables = new HashMap<>();
+ knownVariables.put(name, newIndex);
}
/**
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment