lua的性能优化

0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## lua的性能优化

meteoric 2017-12-07 20:33:00 浏览975

Roberto Ierusalimschy写过经典的Lua 性能提示的文章，链接地址>>

1）多使用local

```print(_VERSION)

local startTime, endTime

startTime = os.clock()

for i = 1, 100 * 10000 do
local x = math.sin(i)
end

endTime = os.clock()

print("[local] used time " .. (endTime - startTime) * 1000 .. " ms")

startTime = os.clock()

local sin = math.sin
for i = 1, 100 * 10000 do
local x = sin(i)
end

endTime = os.clock()

print("[local] used time " .. (endTime - startTime) * 1000 .. " ms")```

```startTime = os.clock()
function foo(x)
for i = 1, 100 * 10000 do
x = x + math.sin(i)
end
return x
end

foo(10)

endTime = os.clock()

print("[foo] used time " .. (endTime - startTime) * 1000 .. " ms")

startTime = os.clock()
function foo2(x)
local sin = math.sin
for i = 1, 100 * 10000 do
x = x + sin(i)
end
return x
end

foo2(10)

endTime = os.clock()

print("[foo2] used time " .. (endTime - startTime) * 1000 .. " ms")```

```startTime = os.clock()
local lim = 10 * 10000
local a = {}
for i = 1, lim do
end

print(a[10]())

endTime = os.clock()

print("used time " .. (endTime - startTime) * 1000 .. " ms")

startTime = os.clock()
function fk(k)
return function() return k end
end

local lim = 10 * 10000
local a = {}
for i = 1, lim do
a[i] = fk(i)
end
endTime = os.clock()

print("used time " .. (endTime - startTime) * 1000 .. " ms")```

2) 字符串拼接，尽可能使用 table 替代

```startTime = os.clock()

local buff = ""
for line in io.lines("C:/Users/zhangyi/Desktop/xxx.txt") do
buff = buff .. line .. "\n"
end

endTime = os.clock()

print(collectgarbage("count") * 1024)

print("used time " .. (endTime - startTime) * 1000 .. " ms")

startTime = os.clock()

local buff = ""
local tbl = {}
for line in io.lines("C:/Users/zhangyi/Desktop/xxx.txt") do
table.insert(tbl, line)
end

buff = table.concat(table, "\n")

endTime = os.clock()

print(collectgarbage("count") * 1024)

print("used time " .. (endTime - startTime) * 1000 .. " ms")```

3) table使用的优化

```startTime = os.clock()
for i = 1, 100 * 10000 do
local a = {}
a[1] = 1
a[2] = 2
a[3] = 3
end
endTime = os.clock()

print("used time " .. (endTime - startTime) * 1000 .. " ms")

startTime = os.clock()
for i = 1, 100 * 10000 do
local a = {true, true, true}
a[1] = 1
a[2] = 2
a[3] = 3
end
endTime = os.clock()

print("used time " .. (endTime - startTime) * 1000 .. " ms")```

```local polyline= {}

for i = 0, 100 * 10000 do
table.insert(polyline, {x = i, y = 1})
end

print(collectgarbage("count") / 1024)```

107.57151889801MB

```local polyline= {}

for i = 0, 100 * 10000 do
table.insert(polyline, {i, 1})
end

print(collectgarbage("count") / 1024)```

77.053853034973MB

```local polyline= {
x = {},
y = {}
}

for i = 0, 100 * 10000 do
table.insert(polyline.x, i)
table.insert(polyline.y, i)
end

print(collectgarbage("count") / 1024)```

32.019150733948MB

meteoric
+ 关注