From 19a37f625fcd502acea42b4f27029c8be724d40c Mon Sep 17 00:00:00 2001 From: Guido Cella Date: Tue, 26 Dec 2023 19:40:41 +0100 Subject: console.lua: refactor find_common_prefix Reuse common_prefix_length() to make find_common_prefix() shorter and faster by not creating many temporary strings. The decrease in the average time to run find_common_prefix() over 1000 calls I measured is: set \: 1e-4s -> 1e-5s set s\Tab>: 1e-5s -> 5e-6s --- player/lua/console.lua | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/player/lua/console.lua b/player/lua/console.lua index b4e722105f..767abc9dd2 100644 --- a/player/lua/console.lua +++ b/player/lua/console.lua @@ -911,19 +911,11 @@ function build_completers() end -- Find the longest common case-sensitive prefix of the entries in "list". -local function find_common_prefix(part, list) - local prefix = nil - - for _, candidate in ipairs(list) do - if prefix and prefix ~= candidate then - local prefix_len = part:len() - while prefix:sub(1, prefix_len + 1) == candidate:sub(1, prefix_len + 1) do - prefix_len = prefix_len + 1 - end - prefix = candidate:sub(1, prefix_len) - else - prefix = candidate - end +local function find_common_prefix(list) + local prefix = list[1] + + for i = 2, #list do + prefix = prefix:sub(1, common_prefix_length(prefix, list[i])) end return prefix @@ -940,7 +932,7 @@ local function complete_match(part, list) end end - local prefix = find_common_prefix(part, completions) + local prefix = find_common_prefix(completions) if opts.case_sensitive then return completions, prefix @@ -957,8 +949,7 @@ local function complete_match(part, list) end end - local lower_case_prefix = find_common_prefix(lower_case_part, - lower_case_completions) + local lower_case_prefix = find_common_prefix(lower_case_completions) -- Behave like GNU readline with completion-ignore-case On. -- part = 'fooBA', completions = {'foobarbaz', 'fooBARqux'} => -- cgit v1.2.3