@@ -52,6 +52,9 @@ public final TruffleString.Encoding getTEncoding(Object object) {
52
52
static final class Cached extends RubyStringLibrary {
53
53
54
54
@ CompilationFinal private boolean seenMutable , seenImmutable , seenOther ;
55
+ @ CompilationFinal private Object cachedEncoding ;
56
+
57
+ private static final Object GENERIC = new Object ();
55
58
56
59
@ Override
57
60
public boolean seen (Object object ) {
@@ -122,26 +125,46 @@ private AbstractTruffleString specializeGetTString(Object object) {
122
125
123
126
@ Override
124
127
public RubyEncoding getEncoding (Object object ) {
128
+ final RubyEncoding encoding ;
125
129
if (seenMutable && object instanceof RubyString ) {
126
- return ((RubyString ) object ).getEncodingUnprofiled ();
130
+ encoding = ((RubyString ) object ).getEncodingUnprofiled ();
127
131
} else if (seenImmutable && object instanceof ImmutableRubyString ) {
128
- return ((ImmutableRubyString ) object ).getEncodingUnprofiled ();
132
+ encoding = ((ImmutableRubyString ) object ).getEncodingUnprofiled ();
133
+ } else {
134
+ CompilerDirectives .transferToInterpreterAndInvalidate ();
135
+ return specializeGetEncoding (object );
129
136
}
130
137
131
- CompilerDirectives .transferToInterpreterAndInvalidate ();
132
- return specializeGetEncoding (object );
138
+ var localCachedEncoding = this .cachedEncoding ;
139
+ if (encoding == localCachedEncoding ) {
140
+ return (RubyEncoding ) localCachedEncoding ;
141
+ } else if (localCachedEncoding == GENERIC ) {
142
+ return encoding ;
143
+ } else {
144
+ CompilerDirectives .transferToInterpreterAndInvalidate ();
145
+ return specializeGetEncoding (object );
146
+ }
133
147
}
134
148
135
149
private RubyEncoding specializeGetEncoding (Object object ) {
150
+ final RubyEncoding encoding ;
136
151
if (object instanceof RubyString ) {
137
152
seenMutable = true ;
138
- return ((RubyString ) object ).getEncodingUnprofiled ();
153
+ encoding = ((RubyString ) object ).getEncodingUnprofiled ();
139
154
} else if (object instanceof ImmutableRubyString ) {
140
155
seenImmutable = true ;
141
- return ((ImmutableRubyString ) object ).getEncodingUnprofiled ();
156
+ encoding = ((ImmutableRubyString ) object ).getEncodingUnprofiled ();
142
157
} else {
143
158
throw CompilerDirectives .shouldNotReachHere ();
144
159
}
160
+
161
+ var localCachedEncoding = this .cachedEncoding ;
162
+ if (localCachedEncoding == null ) {
163
+ this .cachedEncoding = encoding ;
164
+ } else if (encoding != localCachedEncoding ) {
165
+ this .cachedEncoding = GENERIC ;
166
+ }
167
+ return encoding ;
145
168
}
146
169
147
170
@ Override
0 commit comments