亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Lua中實(shí)現(xiàn)StringBuffer功能

 更新時(shí)間:2014年11月06日 12:02:59   投稿:junjie  
這篇文章主要介紹了Lua中實(shí)現(xiàn)StringBuffer功能,本文給出了實(shí)現(xiàn)代碼和調(diào)用代碼,需要的朋友可以參考下

在Lua中,字符串是一個(gè)常量,如果用字符串連接符“..”把2個(gè)字符串連接起來,例如first_str = first_str .. second_str,那么原來的first_str和second_str就會(huì)作為垃圾等待回收,first_str引用的是一個(gè)新的字符串,如果在程序里面有大量的字符串連接操作的話,性能會(huì)十分低下。Lua是一個(gè)很簡(jiǎn)潔的語言,他沒有StringBuffer的實(shí)現(xiàn),但是其實(shí)我們可以動(dòng)手寫一個(gè)簡(jiǎn)單的StringBuffer實(shí)現(xiàn),來避免性能的問題。

首先定義一個(gè)叫StringBuffer的table,使得這個(gè)StringBuffer被調(diào)用的時(shí)候看起來像是面向?qū)ο蟮臉幼?:)
然后分別定義兩個(gè)方法append和tostr,實(shí)現(xiàn)的原理就是:append用table來保存所有字符串,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,既可以避免潛在的性能問題,又可以使得代碼看起來更加易懂~好了,重構(gòu)以前的代碼去了。。。

相關(guān)文章

最新評(píng)論