From 8889ef2f0704b6939eceb39f32a44686be3f8c6c Mon Sep 17 00:00:00 2001 From: Vladimir Panteleev Date: Sat, 24 Nov 2018 08:30:14 +0000 Subject: [PATCH] std.string: Optimize indexOf with start index a bit Use of early returns improves readability and reduces the instruction count in DMD's output. --- std/string.d | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/std/string.d b/std/string.d index f9ce503f1..44e714f69 100644 --- a/std/string.d +++ b/std/string.d @@ -895,15 +895,12 @@ ptrdiff_t indexOf(Char1, Char2)(const(Char1)[] s, const(Char2)[] sub, @safe if (isSomeChar!Char1 && isSomeChar!Char2) { - if (startIdx < s.length) - { - ptrdiff_t foundIdx = indexOf(s[startIdx .. $], sub); - if (foundIdx != -1) - { - return foundIdx + cast(ptrdiff_t) startIdx; - } - } - return -1; + if (startIdx >= s.length) + return -1; + ptrdiff_t foundIdx = indexOf(s[startIdx .. $], sub); + if (foundIdx == -1) + return -1; + return foundIdx + cast(ptrdiff_t) startIdx; } /// Ditto @@ -912,15 +909,12 @@ ptrdiff_t indexOf(Char1, Char2)(const(Char1)[] s, const(Char2)[] sub, @safe if (isSomeChar!Char1 && isSomeChar!Char2) { - if (startIdx < s.length) - { - ptrdiff_t foundIdx = indexOf(s[startIdx .. $], sub, cs); - if (foundIdx != -1) - { - return foundIdx + cast(ptrdiff_t) startIdx; - } - } - return -1; + if (startIdx >= s.length) + return -1; + ptrdiff_t foundIdx = indexOf(s[startIdx .. $], sub, cs); + if (foundIdx == -1) + return -1; + return foundIdx + cast(ptrdiff_t) startIdx; } ///