美文网首页
lua-loadstring和require

lua-loadstring和require

作者: 喜欢吃包包 | 来源:发表于2019-08-29 13:57 被阅读0次

今天发现项目的配置文件是通过loadstring函数生成的table对象,在想用require直接生成table对象
测试了一下,全部的数据生成需要2s的时间,但是用require并没有加快速度。
其实如果是只加载一次的话,loadstring和require速度没什么区别。不过require是会生成一次,loadstring每次都会加载比较耗时间。
data.lua

return {
    testData = 
    {
        test = [[this is a test1]],
        test1 = [[this is a test2]],
        test2 = [[this is a test3]],
        test3 = [[this is a test4]],
        test4 = [[this is a test5]],
        test5 = [[this is a test6]],
        test6 = [[this is a test7]],
        test7 = [[this is a test8]],
        test8 = [[this is a test9]],
    }
}

test.lua

local data = require("data")

print("-------")
print(data.testData.test1)
print(data.testData.test2)

local testTime = 1000000

local dataStr 
local file = io.open("data.lua")
dataStr = file:read("*all")
print(dataStr)

local chunk = loadstring(dataStr)
local _, dataTable = pcall(chunk)

print("-------")
print(dataTable.testData.test1)
print(dataTable.testData.test2)

local startTime = os.time()
for i=1,testTime do
    local chunk = loadstring(dataStr)
    pcall(chunk)
end
local endTime = os.time()

print("loadstring time:" .. (endTime - startTime))

startTime = os.time()
for i=1,testTime do
    require("data")
end
endTime = os.time()

print("require time:" .. (endTime - startTime))
1567058232503.jpg

相关文章

网友评论

      本文标题:lua-loadstring和require

      本文链接:https://www.haomeiwen.com/subject/wsriectx.html