問題描述
本機 Lua 中的高效可變字節數組 (Efficient mutable byte array in native Lua)
我正在嘗試在本地 Lua 中高效地實現 LZ77 解碼器(即沒有 C 庫,並且不依賴於非核心 Lua 庫) ‑ 請參閱 liblzg.
對於加載和解析二進製文件,Lua 字符串可以完美運行,並且性能良好(例如使用 s:byte(k) 方法) . 但是,對於創建解碼後的輸出數據,字符串並不是非常理想的,因為它們是不可變的,並且當輸出變大時,字符串連接往往會花費很多時間。
解碼器必須能夠:
- 一次將一個字節附加到輸出(最多數百萬次)
- 從輸出緩衝區讀取(或多或少隨機訪問)
什麼是最好的選擇?輸出數據的大小是事先知道的,因此可以預先分配。
參考解法
方法 1:
Avoid string concatenation: save output strings to a table and write all strings in it at the end. If you're concerned about the table getting too big, flush it periodically. See http://www.lua.org/pil/11.6.html
方法 2:
Sounds like a perfect job for table.concat
your output is just a table of bytes.
When you need to copy, you do it as you normally would for a table. eg:
for i=#output‑5,9 do output[#output+1]=output[i] end
When you finally are done with the output stream, convert it to a string with str=table.concat(output)
(by marcus256、lhf、daurnimator)