Skip to content

Commit 75b48ef

Browse files
authored
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 parent 57874ce commit 75b48ef

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

lib/std/mem.zig

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1344,7 +1344,11 @@ pub fn lastIndexOf(comptime T: type, haystack: []const T, needle: []const T) ?us
13441344
/// Uses Boyer-Moore-Horspool algorithm on large inputs; `indexOfPosLinear` on small inputs.
13451345
pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, needle: []const T) ?usize {
13461346
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

13491353
if (!meta.trait.hasUniqueRepresentation(T) or haystack.len < 52 or needle.len <= 4)
13501354
return indexOfPosLinear(T, haystack, start_index, needle);

0 commit comments

Comments
 (0)