在Lua中,字符串是一個(gè)常量,如果用字符串連接符“..”把2個(gè)字符串連接起來(lái),例如first_str = first_str .. second_str,那么原來(lái)的first_str和second_str就會(huì)作為垃圾等待回收,first_str引用的是一個(gè)新的字符串,如果在程序里面有大量的字符串連接操作的話,性能會(huì)十分低下。Lua是一個(gè)很簡(jiǎn)潔的語(yǔ)言,他沒有StringBuffer的實(shí)現(xiàn),但是其實(shí)我們可以動(dòng)手寫一個(gè)簡(jiǎn)單的StringBuffer實(shí)現(xiàn),來(lái)避免性能的問題。
首先定義一個(gè)叫StringBuffer的table,使得這個(gè)StringBuffer被調(diào)用的時(shí)候看起來(lái)像是面向?qū)ο蟮臉幼?:)
然后分別定義兩個(gè)方法append和tostr,實(shí)現(xiàn)的原理就是:append用table來(lái)保存所有字符串,tostr把保存了字符串的table用concat轉(zhuǎn)成真正的字符串。
復(fù)制代碼 代碼如下:
StringBuffer = {}
StringBuffer.append = function(t, str)
if t and str then
table.insert(t, str)
end
end
StringBuffer.tostr = function(t)
if t then
return table.concat(t)
end
end
StringBuffer.new = function() return {} end
調(diào)用的時(shí)候大概如下,摘錄了一段代碼。。。
復(fù)制代碼 代碼如下:
all_assets = StringBuffer.new()
for asset in ctx:allassets() do
StringBuffer.append(all_assets, asset:id())
StringBuffer.append(all_assets, ', ')
end
result = StringBuffer.tostr(all_assets)
print (result)
在Lua中實(shí)現(xiàn)這樣的一個(gè)StringBuffer,既可以避免潛在的性能問題,又可以使得代碼看起來(lái)更加易懂~好了,重構(gòu)以前的代碼去了。。。
您可能感興趣的文章:- js實(shí)現(xiàn)StringBuffer的簡(jiǎn)單實(shí)例
- JavaScript實(shí)現(xiàn)Java中StringBuffer的方法
- 淺談js中StringBuffer類的實(shí)現(xiàn)方法及使用