From 1b7ccdcf33b744da7d8a3da9e736582867e66e57 Mon Sep 17 00:00:00 2001 From: Noah <33094578+coolreader18@users.noreply.github.com> Date: Wed, 19 May 2021 20:32:08 -0500 Subject: [PATCH] Skip .chars().len() when str is ascii --- vm/src/builtins/pystr.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/vm/src/builtins/pystr.rs b/vm/src/builtins/pystr.rs index 62d1091f6..7aee0e557 100644 --- a/vm/src/builtins/pystr.rs +++ b/vm/src/builtins/pystr.rs @@ -301,7 +301,13 @@ impl PyStr { } #[cold] fn _compute_char_len(&self) -> usize { - let len = self.value.chars().count(); + // doing the check is ~10x faster for ascii, and is actually only 2% slower worst case for + // non-ascii; see https://github.com/RustPython/RustPython/pull/2586#issuecomment-844611532 + let len = if self.value.is_ascii() { + self.value.len() + } else { + self.value.chars().count() + }; // len cannot be usize::MAX, since vec.capacity() < isize::MAX self.char_len.store(len, atomic::Ordering::Relaxed); len