From 3170ad2ee3115cfc7725055101c06607a8a8b081 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Tue, 7 May 2024 12:27:03 +0200 Subject: [PATCH] LibJS: Avoid string trimming in GlobalObject.parseInt() when possible In the common case, parseInt() is being called with strings that don't have leading whitespace. By checking for that first, we can avoid the cost of trimming and multiple malloc/GC allocations. --- Userland/Libraries/LibJS/Runtime/GlobalObject.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp index 39ce41ff8c8..9e78b3334a8 100644 --- a/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/GlobalObject.cpp @@ -303,7 +303,13 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_int) auto input_string = TRY(string.to_string(vm)); // 2. Let S be ! TrimString(inputString, start). - auto trimmed_string = MUST(trim_string(vm, PrimitiveString::create(vm, move(input_string)), TrimMode::Left)); + String trimmed_string; + // OPTIMIZATION: We can skip the trimming step when the value already starts with an alphanumeric ASCII character. + if (input_string.is_empty() || is_ascii_alphanumeric(input_string.bytes_as_string_view()[0])) { + trimmed_string = input_string; + } else { + trimmed_string = MUST(trim_string(vm, PrimitiveString::create(vm, move(input_string)), TrimMode::Left)); + } // 3. Let sign be 1. auto sign = 1;