下面分别对比四种情景来分析内存占用的不同。因为lua在使用 .. 连接字符串时,底层会调用luaV_concat -> luaS_newStr新建字符串,这里对比下在创建短字符串和长字符串后的内存消耗:
Lua5.3.4
情景1:
相同短字符串
collectgarbage("stop"); --close auto gc
collectgarbage("collect") --full gc
local before = collectgarbage("count");
for i = 1, 10000 do
local string = "100000000000000000000000" .. "0"
end
local after = collectgarbage("count");
print("short same mem cost:" .. (after - before) .. "K" )
short same mem cost:0.580078125K
情景2:
相同长字符串
collectgarbage("stop"); --close auto gc
collectgarbage("collect") --full gc
before = collectgarbage("count");
for i = 1, 10000 do
local string = "10000000000000000000000000000000000000000000000000000" .. "0"
end
after = collectgarbage("count");
print("long same mem cost:" .. (after - before) .. "K" )
long same mem cost:771.48K
通过对比:在创建相同字符串时,因为短字符串在StringTable只有一份拷贝,而长字符串每次都会产生新的数据拷贝,所以消耗内存差异明显。 0.58K VS 771.48K
Lua5.3.4
情景3:
不同短字符串
collectgarbage("stop"); --close auto gc
collectgarbage("collect") --full gc
local before = collectgarbage("count");
for i = 1, 10000 do
local string = "100000000000000000000000" .. i
end
local after = collectgarbage("count");
print("short diff mem cost:" .. (after - before) .. "K" )
short diff mem cost:1052.62109375K
情景4:
不同长字符串
collectgarbage("stop"); --close auto gc
collectgarbage("collect") --full gc
for i = 1, 10000 do
local string = "10000000000000000000000000000000000000000000000000000" .. i
end
after = collectgarbage("count");
print("long diff mem cost:" .. (after - before) .. "K" )
long diff mem cost:1145.82421875K