Skip to content

Commit 5ecd9e4

Browse files
committed
perf(rust): substring search with memchr, split without a string per piece
includes, indexOf, split and string replace set up the standard library's two-way searcher on every call. They use memchr::memmem, already in the tree through regress and oxc. split copies the text once and puts short pieces in the buffer short strings share (Strings::alloc_str).
1 parent 27a7044 commit 5ecd9e4

5 files changed

Lines changed: 50 additions & 9 deletions

File tree

‎rust/Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎rust/crates/psychoscript/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ icu_datetime = { version = "2.4", default-features = false, features = ["compile
2626
# Number and BigInt `toLocaleString`; already dependencies of icu_datetime.
2727
icu_decimal = { version = "2.4", default-features = false, features = ["compiled_data"] }
2828
fixed_decimal = { version = "0.7", default-features = false }
29+
# Substring search for `includes`, `indexOf`, `split` and `replace`; already a dependency of regress and oxc.
30+
memchr = "2"
2931
# Parses the locale tags `localeCompare` takes; already a dependency of icu_collator.
3032
icu_locale_core = { version = "2.4", default-features = false }
3133
# Time zone inputs (`ZonedDateTime`, `ZoneNameTimestamp`) for `icu_datetime`.

‎rust/crates/psychoscript/src/builtins/string.rs‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -414,13 +414,20 @@ fn s_at(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> Res {
414414
})
415415
}
416416

417+
/// Where `needle` first is in `hay`, in bytes. The standard library's search sets up a two-way searcher for each
418+
/// call, which costs more than the search itself for the short needles programs look for.
419+
#[inline]
420+
fn find_text(hay: &str, needle: &str) -> Option<usize> {
421+
memchr::memmem::find(hay.as_bytes(), needle.as_bytes())
422+
}
423+
417424
/// Finds `needle` in `hay` at or after code unit `from`, in code units.
418425
fn find16(hay: StrRef, needle: StrRef, from: usize) -> Option<usize> {
419426
if hay.ascii && needle.ascii {
420427
if from > hay.s.len() {
421428
return None;
422429
}
423-
return hay.s[from..].find(needle.s).map(|i| i + from);
430+
return find_text(&hay.s[from..], needle.s).map(|i| i + from);
424431
}
425432
let h = hay.utf16();
426433
let n = needle.utf16();
@@ -767,13 +774,20 @@ fn split(vm: &mut Vm, c: &mut Conversions, s: StrId, args: &[Value]) -> Res {
767774
.map(|p| Value::Str(vm.atoms.alloc_units(p)))
768775
.collect()
769776
} else {
770-
let pieces: Vec<String> = vm
771-
.text(s)
772-
.split(vm.text(sep))
773-
.take(limit)
774-
.map(str::to_owned)
775-
.collect();
776-
pieces.into_iter().map(|p| vm.string_val(p)).collect()
777+
// One copy of the text and one searcher for the separator, then each piece is a short string.
778+
let (text, sep) = (vm.text(s).to_owned(), vm.text(sep).to_owned());
779+
let finder = memchr::memmem::Finder::new(sep.as_bytes());
780+
let mut pieces = Vec::new();
781+
let mut from = 0;
782+
while pieces.len() < limit {
783+
let at = finder.find(&text.as_bytes()[from..]).map(|i| from + i);
784+
pieces.push(vm.string_of_str(&text[from..at.unwrap_or(text.len())]));
785+
match at {
786+
Some(at) => from = at + sep.len(),
787+
None => break,
788+
}
789+
}
790+
pieces
777791
}
778792
}
779793
};
@@ -875,7 +889,7 @@ fn replace_in(vm: &mut Vm, c: &mut Conversions, s: StrId, args: &[Value], all: b
875889
}
876890
} else {
877891
let mut from = 0;
878-
while let Some(i) = subject[from..].find(&needle) {
892+
while let Some(i) = find_text(&subject[from..], &needle) {
879893
positions.push(from + i);
880894
from += i + needle.len();
881895
if !all {

‎rust/crates/psychoscript/src/strings.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,19 @@ impl Strings {
247247
s
248248
}
249249

250+
/// A string of text borrowed from elsewhere, a piece of another string as a rule. A short one goes at the end of
251+
/// the buffer short strings share, so it allocates nothing of its own.
252+
pub fn alloc_str(&mut self, s: &str) -> StrId {
253+
if s.len() >= GROW_MIN || !s.is_ascii() {
254+
return self.alloc(s.to_owned());
255+
}
256+
let g = self.arena();
257+
let mut buf = std::mem::take(&mut self.grow[g]);
258+
let start = buf.len();
259+
buf.push_str(s);
260+
self.push_grown(buf, g, start, true)
261+
}
262+
250263
/// The strings a compile starts from: the fresh runtime's (`builtins::image`), so they have the same ids in
251264
/// every run and a run's VM is a copy of the image.
252265
pub fn fresh() -> Self {

‎rust/crates/psychoscript/src/vm.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -647,6 +647,17 @@ impl Vm {
647647
Value::Str(self.atoms.alloc(s))
648648
}
649649

650+
/// `string_val` of borrowed text (`Strings::alloc_str`).
651+
pub fn string_of_str(&mut self, s: &str) -> Value {
652+
if self.atoms.bufs.len() >= MAX_STRINGS {
653+
self.out_of_memory();
654+
}
655+
if let Some(m) = self.heap_meter.as_deref_mut() {
656+
m.debt += 2 * s.len() as u64;
657+
}
658+
Value::Str(self.atoms.alloc_str(s))
659+
}
660+
650661
/// The interned string for a fixed text, without allocating a new one each time.
651662
pub fn static_str(&mut self, s: &str) -> Value {
652663
let a = self.atoms.intern(s);

0 commit comments

Comments
 (0)