Skip to content

Commit

Permalink
perf: range string instead of regex
Browse files Browse the repository at this point in the history
  • Loading branch information
glepnir committed Aug 26, 2024
1 parent c5982c7 commit b02fbaf
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 6 deletions.
34 changes: 34 additions & 0 deletions bench/space_or_tab.lua
Original file line number Diff line number Diff line change
@@ -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
15 changes: 9 additions & 6 deletions lua/indentmini/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,17 @@ local get_sw_value, get_indent_lnum = C.get_sw_value, C.get_indent_lnum
--- @field snapshot table<integer, Snapshot>
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
Expand All @@ -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
Expand Down

0 comments on commit b02fbaf

Please sign in to comment.