From 75b48ef503204d3ba005647ecce8fda4657a8588 Mon Sep 17 00:00:00 2001 From: Karl Seguin Date: Mon, 9 Oct 2023 21:50:16 +0800 Subject: [PATCH] std.mem: use indexOfScalarPos when indexOf is called where needle.len == 1 When `std.mem.indexOf` is called with a single-item needle, use `indexOfScalarPos` which is significantly faster than the more general `indexOfPosLinear`. This can be done without introducing overhead to normal cases (where `needle.len > 1`). --- lib/std/mem.zig | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/std/mem.zig b/lib/std/mem.zig index b6bc492cda8d35a2647e1f95646e7f9bf41620b2..8ed2943ec0b05b5309d8241dadf00ec99bd3eb24 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -1344,7 +1344,11 @@ pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?us /// Uses Boyer-Moore-Horspool algorithm on large inputs; `indexOfPosLinear` on small inputs. pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize { if (needle.len > haystack.len) return null; - if (needle.len == 0) return start_index; + if (needle.len < 2) { + if (needle.len == 0) return start_index; + // indexOfScalarPos is significantly faster than indexOfPosLinear + return indexOfScalarPos(T, haystack, start_index, needle[0]); + } if (!meta.trait.hasUniqueRepresentation(T) or haystack.len < 52 or needle.len <= 4) return indexOfPosLinear(T, haystack, start_index, needle); -- 2.54.0