From e8873e01b67629f93ebbd83397f2454e16e0d864 Mon Sep 17 00:00:00 2001 From: Takashi Kokubun Date: Sat, 5 Nov 2022 00:26:32 -0700 Subject: [PATCH] [ruby/erb] Use strpbrk only when str is long enough for SIMD This is the same trick used by https://github.com/k0kubun/hescape to choose the best strategy for different scenarios. https://github.com/ruby/erb/commit/af26da2858 --- ext/erb/erb.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/ext/erb/erb.c b/ext/erb/erb.c index 1e4842c793..1c3371d24e 100644 --- a/ext/erb/erb.c +++ b/ext/erb/erb.c @@ -38,9 +38,8 @@ escaped_length(VALUE str) static VALUE optimized_escape_html(VALUE str) { - // Optimize the most common, no-escape case with strpbrk(3). Not using it after - // this because calling a C function many times could be slower for some cases. - if (strpbrk(RSTRING_PTR(str), "'&\"<>") == NULL) { + // Use strpbrk to optimize the no-escape case when str is long enough for SIMD. + if (RSTRING_LEN(str) >= 16 && strpbrk(RSTRING_PTR(str), "'&\"<>") == NULL) { return str; } @@ -62,8 +61,11 @@ optimized_escape_html(VALUE str) } } - VALUE escaped = rb_str_new(buf, dest - buf); - preserve_original_state(str, escaped); + VALUE escaped = str; + if (RSTRING_LEN(str) < (dest - buf)) { + escaped = rb_str_new(buf, dest - buf); + preserve_original_state(str, escaped); + } ALLOCV_END(vbuf); return escaped; }