Skip to content

Instantly share code, notes, and snippets.

@Yonaba
Last active December 22, 2015 23:39
Show Gist options
  • Save Yonaba/6548184 to your computer and use it in GitHub Desktop.
Save Yonaba/6548184 to your computer and use it in GitHub Desktop.
string.gmatch vs string.sub
-- Calls f(...) n-times
local function time(nm,times, f,...)
local st = os.clock()
for i = 1, times do
f(...)
end
local et = os.clock()
print(('(%s): Times (%d): %.2f ms')
:format(nm, times, (et-st)*1000))
end
-- string.sub test
local function test_sub(str)
local char
for i = 1, #str do
char = str:sub(i,i)
end
end
-- string.gmatch test
local function test_gmatch(str)
for i in str:gmatch('.') do
end
end
-- Makes a string
local function make_string(len)
local str = ''
for i = 1,len do
local s = string.char(math.random(255))
str = str .. s
end
return str
end
math.randomseed(os.time())
local str = make_string(1e4)
time('gmatch', 1000, test_gmatch, str)
time( 'sub', 1000, test_sub, str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment