Skip to content

Instantly share code, notes, and snippets.

@HybridDog
Last active July 5, 2016 08:23
Show Gist options
  • Save HybridDog/eff24a68cb17990d095d0a1bb5a14837 to your computer and use it in GitHub Desktop.
Save HybridDog/eff24a68cb17990d095d0a1bb5a14837 to your computer and use it in GitHub Desktop.
string to table benchmark test
local function subtt(str)
local t = {}
for i = 1, #str do
t[i] = str:sub(i, i)
end
return t
end
local function gsubtt(str)
local t = {}
local i = 1
str:gsub(".", function(c)
t[i] = c
i = i+1
end)
return t
end
local txt = [[
local function subtt(str)
local t = {}
for i = 1, #str do
t[i] = str:sub(i, i)
end
return t
end
local function gsubtt(str)
local t = {}
local i = 1
str:gsub(".", function(c)
t[i] = c
i = i+1
end)
return t
end
]]
local function bt()
local s = benchmark_function(subtt, txt)
local g = benchmark_function(gsubtt, txt)
print("s", s)
print("g", g)
print(dump(subtt(txt)) == dump(gsubtt(txt)))
end
minetest.register_chatcommand("bt", {
params = "a",
description = "ahref",
func = bt,
})
--[[ result:
subtt is ~between 3 (long txt) and 6 (short text) times as fast as gsubtt
]]
------------------------------------------------------------------------------------------------------
function string.charIter(txt)
-- return txt:gmatch"."
local i = 0
local l = #txt
return function()
i = i+1
if i > l then
return
end
return txt:sub(i, i), i
end
end
local function gsubtt(str)
for c in str:gmatch"." do
end
end
local function subtt(str)
for c,i in str:charIter() do
end
end
local txt = [[
local function subtt(str)
local t = {}
for i = 1, #str do
t[i] = str:sub(i, i)
end
return t
end
local function gsubtt(str)
local t = {}
local i = 1
str:gsub(".", function(c)
t[i] = c
i = i+1
end)
return t
end
]]
local function bt()
local s = benchmark_function(subtt, txt)
local g = benchmark_function(gsubtt, txt)
print("s", s)
print("g", g)
print(dump(subtt(txt)) == dump(gsubtt(txt)), s/g)
end
minetest.register_chatcommand("bt", {
params = "a",
description = "ahref",
func = bt,
})
--[[ result:
s 200267.1995992
g 68422.226311095
true 2.9269319400489
2016-07-05 10:22:05: ACTION[Server]: msg to singleplayer: "@#f3d2ff) (4.000136 s)@#ffffff)"
s 204012.3979938
g 69244.223023108
true 2.9462731919993
2016-07-05 10:22:11: ACTION[Server]: msg to singleplayer: "@#f3d2ff) (4.000134 s)@#ffffff)"
s 205426.89728655
g 68805.465597267
true 2.9856188822115
2016-07-05 10:22:23: ACTION[Server]: msg to singleplayer: "@#f3d2ff) (4.000122 s)@#ffffff)"
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment