Lua 字符串拼接方法测试

字符串拼接方法测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function test_spot(count, str)
local result = ""
for i=0,count do
result = result..str
end
end

function test_table_concat(count, str)
local tbl = {}
for i=0,count do
table.insert(tbl, str)
end
table.concat(tbl)
end

print("单个字符串拼接多次")
local startTime = os.clock()
test_spot(10000, "123")
local endTime = os.clock()
print(string.format("spot use time => %.4f", endTime - startTime))

startTime = os.clock()
test_table_concat(10000, "123")
endTime = os.clock()
print(string.format("table_concat use time => %.4f", endTime - startTime))

function test_little_spot(count, str)
for i=0,count do
local tmp = str..str..str..str..str
end
end

function test_little_table_concat(count, str)
for i=0,count do
local tbl = {}
for i=0,5 do
table.insert(tbl, str)
end
table.concat(tbl)
end
end

print("小字符串拼接多次")
startTime = os.clock()
test_little_spot(10000, "123")
endTime = os.clock()
print(string.format("little_spot use time => %.4f", endTime - startTime))

startTime = os.clock()
test_little_table_concat(10000, "123")
endTime = os.clock()
print(string.format("little_table_concat use time => %.4f", endTime - startTime))
1
2
3
4
5
6
单个字符串拼接多次
spot use time => 0.0300
table_concat use time => 0.0000
小字符串拼接多次
little_spot use time => 0.0000
little_table_concat use time => 0.0200