From b02fbaf090260d97005bef82a55bb5767354528d Mon Sep 17 00:00:00 2001 From: glepnir Date: Mon, 26 Aug 2024 14:20:36 +0800 Subject: [PATCH] perf: range string instead of regex --- bench/space_or_tab.lua | 34 ++++++++++++++++++++++++++++++++++ lua/indentmini/init.lua | 15 +++++++++------ 2 files changed, 43 insertions(+), 6 deletions(-) create mode 100644 bench/space_or_tab.lua diff --git a/bench/space_or_tab.lua b/bench/space_or_tab.lua new file mode 100644 index 0000000..b23351c --- /dev/null +++ b/bench/space_or_tab.lua @@ -0,0 +1,34 @@ +local function only_spaces_or_tabs(text) + for i = 1, #text do + local c = text:sub(i, i) + if c ~= ' ' and c ~= '\t' then + return false + end + end + return true +end + +local function only_spaces_or_tabs_regex(text) + return not text:find('[^ \t]') +end + +local function benchmark(func, text, iterations) + local start_time = os.clock() + for _ = 1, iterations do + func(text) + end + local end_time = os.clock() + return end_time - start_time +end + +local text = ' \t\t ' -- Example text to test +local iterations = 1000000 -- Number of iterations for the benchmark + +local time1 = benchmark(only_spaces_or_tabs, text, iterations) +local time2 = benchmark(only_spaces_or_tabs_regex, text, iterations) + +print('Time for only_spaces_or_tabs:', time1) +print('Time for only_spaces_or_tabs_regex:', time2) + +-- Time for only_spaces_or_tabs: 0.07258 +-- Time for only_spaces_or_tabs_regex: 0.093389 diff --git a/lua/indentmini/init.lua b/lua/indentmini/init.lua index 2cf17dd..8f13b90 100644 --- a/lua/indentmini/init.lua +++ b/lua/indentmini/init.lua @@ -38,11 +38,17 @@ local get_sw_value, get_indent_lnum = C.get_sw_value, C.get_indent_lnum --- @field snapshot table local context = { snapshot = {} } ---- check text only has space or tab +--- check text only has space or tab see bench/space_or_tab.lua --- @param text string --- @return boolean true only have space or tab local function only_spaces_or_tabs(text) - return text:match('^[ \t]*$') ~= nil + for i = 1, #text do + local c = text:sub(i, i) + if c ~= ' ' and c ~= '\t' then + return false + end + end + return true end --- @param bufnr integer @@ -62,10 +68,7 @@ local function make_snapshot(lnum) if is_empty then local prev_lnum = lnum - 1 while prev_lnum >= 1 do - if not context.snapshot[prev_lnum] then - context.snapshot[prev_lnum] = make_snapshot(prev_lnum) - end - local sp = context.snapshot[prev_lnum] + local sp = context.snapshot[prev_lnum] or make_snapshot(prev_lnum) if (not sp.is_empty and sp.indent == 0) or (sp.indent > 0) then if sp.indent > 0 then indent = sp.indent