Skip to content

Commit ab55da5

Browse files
kaezakwolekr
authored andcommittedDec 29, 2014
Faster string.split implementation.
1 parent 86cfbc2 commit ab55da5

File tree

1 file changed

+22
-22
lines changed

1 file changed

+22
-22
lines changed
 

‎builtin/common/misc_helpers.lua

+22-22
Original file line numberDiff line numberDiff line change
@@ -155,33 +155,33 @@ function dump(o, indent, nested, level)
155155
end
156156

157157
--------------------------------------------------------------------------------
158-
function string.split(str, delim, include_empty, max_splits)
158+
-- Localize functions to avoid table lookups (better performance).
159+
local table_insert = table.insert
160+
local str_sub, str_find = string.sub, string.find
161+
function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
159162
delim = delim or ","
160-
max_splits = max_splits or 0
161-
local fields = {}
162-
local num_splits = 0
163-
local last_pos = 0
164-
for part, pos in str:gmatch("(.-)[" .. delim .. "]()") do
165-
last_pos = pos
166-
if include_empty or part ~= "" then
167-
num_splits = num_splits + 1
168-
fields[num_splits] = part
169-
if max_splits > 0 and num_splits + 1 >= max_splits then
170-
break
171-
end
163+
max_splits = max_splits or -1
164+
local items = {}
165+
local pos, len, seplen = 1, #str, #delim
166+
local plain = not sep_is_pattern
167+
max_splits = max_splits + 1
168+
repeat
169+
local np, npe = str_find(str, delim, pos, plain)
170+
np, npe = (np or (len+1)), (npe or (len+1))
171+
if (not np) or (max_splits == 1) then
172+
np = len + 1
173+
npe = np
172174
end
173-
end
174-
-- Handle the last field
175-
if max_splits <= 0 or num_splits <= max_splits then
176-
local last_part = str:sub(last_pos)
177-
if include_empty or last_part ~= "" then
178-
fields[num_splits + 1] = last_part
175+
local s = str_sub(str, pos, np - 1)
176+
if include_empty or (s ~= "") then
177+
max_splits = max_splits - 1
178+
table_insert(items, s)
179179
end
180-
end
181-
return fields
180+
pos = npe + 1
181+
until (max_splits == 0) or (pos > len)
182+
return items
182183
end
183184

184-
185185
--------------------------------------------------------------------------------
186186
function file_exists(filename)
187187
local f = io.open(filename, "r")

0 commit comments

Comments
 (0)
Please sign in to comment.