Skip to content

Instantly share code, notes, and snippets.

@cloudwu
Last active August 28, 2021 09:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cloudwu/282e9e95e295c50c2159 to your computer and use it in GitHub Desktop.
Save cloudwu/282e9e95e295c50c2159 to your computer and use it in GitHub Desktop.
Test escape
--[[
In windows 7 64, Intel i5-2500 CPU @ 3.30 GHz
$ lua testescape.lua old
Total string 44128
use time: 0.197
use mem: 18130.474609375
$ lua testescape.lua new
Total string 44128
use time: 0.134
use mem: 6585.3671875
]]
local test
function gen()
test = {}
local s = "&<>abcdefghijklmnoperstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
math.randomseed(os.time())
local random = math.random
local function randomstring(range, n)
local r = string.rep(" ", n):gsub(".", function() local r = random(1, range) return s:sub(r,r) end)
return r
end
for i = 10, #s do
for j = 4, 200 do
for k = 1,4 do
table.insert(test, randomstring(i,j))
end
end
end
print("Total string", #test)
end
local function old_escape_data(data)
data = string.gsub(data, '&', '&amp;')
data = string.gsub(data, '<', '&lt;')
data = string.gsub(data, '>', '&gt;')
return data
end
local escape_data_tbl = {
['&'] = '&amp;',
['<'] = '&lt;',
['>'] = '&gt;',
}
local function new_escape_data(data)
return string.gsub(data, '[&<>]', escape_data_tbl)
end
local function test_func(f)
gen()
collectgarbage "collect"
collectgarbage "stop"
local mem = collectgarbage "count"
local ti = os.clock()
for _, s in ipairs(test) do
f(s)
end
print("use time:", os.clock() - ti)
print("use mem:", collectgarbage "count" - mem)
end
function old()
test_func(old_escape_data)
end
function new()
test_func(new_escape_data)
end
local mode = ...
assert(_G[mode])()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment