authorgravatar for karlseguin@users.noreply.github.comKarl Seguin <karlseguin@users.noreply.github.com> 2023-10-09 21:50:16+08:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-10-09 16:50:16+03:00
log75b48ef503204d3ba005647ecce8fda4657a8588
treee84b4d576938585c06f94b498785e6539bd60938
parent57874ce619c098a4affd6804a71e0604ff3874c8
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

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`).

1 files changed, 5 insertions(+), 1 deletions(-)

lib/std/mem.zig+5-1
...@@ -1344,7 +1344,11 @@ pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?us...@@ -1344,7 +1344,11 @@ pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?us
1344/// Uses Boyer-Moore-Horspool algorithm on large inputs; `indexOfPosLinear` on small inputs.1344/// Uses Boyer-Moore-Horspool algorithm on large inputs; `indexOfPosLinear` on small inputs.
1345pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize {1345pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize {
1346 if (needle.len > haystack.len) return null;1346 if (needle.len > haystack.len) return null;
1347 if (needle.len == 0) return start_index;1347 if (needle.len < 2) {
1348 if (needle.len == 0) return start_index;
1349 // indexOfScalarPos is significantly faster than indexOfPosLinear
1350 return indexOfScalarPos(T, haystack, start_index, needle[0]);
1351 }
13481352
1349 if (!meta.trait.hasUniqueRepresentation(T) or haystack.len < 52 or needle.len <= 4)1353 if (!meta.trait.hasUniqueRepresentation(T) or haystack.len < 52 or needle.len <= 4)
1350 return indexOfPosLinear(T, haystack, start_index, needle);1354 return indexOfPosLinear(T, haystack, start_index, needle);