summaryrefslogtreecommitdiff
path: root/string.c
diff options
authorJean Boussier <jean.boussier@gmail.com>2024-11-27 10:32:57 +0100
committerJean Boussier <jean.boussier@gmail.com>2024-11-27 14:50:07 +0100
commit26d020cb6ea98adb38b370cf49b8101292d6f193 (patch)
treeb93424b5f7a000538310340b445b5a27aef7c6be /string.c
parent43b059b6a3b5c49b7d883c49dd1200580c1f92be (diff)
Optimize `rb_must_asciicompat`
While profiling `strscan`, I noticed `rb_must_asciicompat` was quite slow, as more than 5% of the benchmark was spent in it: https://share.firefox.dev/49bOcTn By checking for the common 3 ASCII compatible encoding index first, we can skip a lot of expensive operations in the happy path.
Notes
Notes: Merged: https://github.com/ruby/ruby/pull/12180
Diffstat (limited to 'string.c')
-rw-r--r--string.c11
1 files changed, 9 insertions, 2 deletions
diff --git a/string.c b/string.c
index b970c5c6f5..2f89e3c141 100644
--- a/string.c
+++ b/string.c
@@ -2691,10 +2691,17 @@ str_discard(VALUE str)
void
rb_must_asciicompat(VALUE str)
{
- rb_encoding *enc = rb_enc_get(str);
- if (!enc) {
+ int encindex = rb_enc_get_index(str);
+
+ if (RB_UNLIKELY(encindex == -1)) {
rb_raise(rb_eTypeError, "not encoding capable object");
}
+
+ if (RB_LIKELY(str_encindex_fastpath(encindex))) {
+ return;
+ }
+
+ rb_encoding *enc = rb_enc_from_index(encindex);
if (!rb_enc_asciicompat(enc)) {
rb_raise(rb_eEncCompatError, "ASCII incompatible encoding: %s", rb_enc_name(enc));
}
close