From 5e7b8b5d3e4820312b56001d592ac8f5320509d6 Mon Sep 17 00:00:00 2001 From: Aapo Talvensaari Date: Mon, 10 Feb 2025 10:19:50 +0000 Subject: [PATCH] perf(tools/string): a way faster strip function ### Summary In https://github.com/Kong/kong/pull/13168 I made this already faster, but this time I managed to make it a way faster. Signed-off-by: Aapo Talvensaari --- kong/tools/string.lua | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/kong/tools/string.lua b/kong/tools/string.lua index 4c12e571583..41865fc0047 100644 --- a/kong/tools/string.lua +++ b/kong/tools/string.lua @@ -45,34 +45,26 @@ _M.strip = function(value) return "" end - local len = #value local s = 1 -- position of the leftmost non-whitespace char - for i = 1, len do - local b = byte(value, i) - if b == SPACE_BYTE or (b >= TAB_BYTE and b <= CR_BYTE) then - s = s + 1 - else - break - end - end - - if s > len then + ::spos:: + local b = byte(value, s) + if not b then -- reached the end of the all whitespace string return "" end + if b == SPACE_BYTE or (b >= TAB_BYTE and b <= CR_BYTE) then + s = s + 1 + goto spos + end - local e = len -- position of the rightmost non-whitespace char - if s < e then - for i = e, 1, -1 do - local b = byte(value, i) - if b == SPACE_BYTE or (b >= TAB_BYTE and b <= CR_BYTE) then - e = e - 1 - else - break - end - end + local e = -1 -- position of the rightmost non-whitespace char + ::epos:: + b = byte(value, e) + if b == SPACE_BYTE or (b >= TAB_BYTE and b <= CR_BYTE) then + e = e - 1 + goto epos end - if s ~= 1 or e ~= len then + if s ~= 1 or e ~= -1 then value = sub(value, s, e) end