-copy自云风的blog
lua 的整体效率是很高的,其中,它的 table 实现的很巧妙为这个效率贡献很大。
lua 的 table 充当了数组和映射表的双重功能,所以在实现时就考虑了这些,让 table 在做数组使用时尽量少效率惩罚。
lua 是这样做的。它把一个 table 分成数组段和 hash 段两个部分。数字 key 一般放在数组段中,没有初始化过的 key 值全部设置为 nil 。当数字 key 过于离散的时候,部分较大的数字 key 会被移到 hash段中去。这个分割线是以数组段的利用率不低于 50% 为准。 0 和 负数做 key 时是肯定放在 hash 段中的。
string 和 number 都放在一起做 hash ,分别有各自的算法,但是 hash 的结果都在一个数值段中。hash 段采用闭散列方法,即,所有的值都存在于表中。如果hash 发生碰撞,额外的数据记在空闲槽位里,而不额外分配空间存放。当整个个表放满后,hash 段会扩大,所有段内的数据将被重新 hash ,重新 hash 后,冲突将大大减少。
这种 table 的实现策略,首先保证的是查找效率。对于把 table 当数组使用时将和 C 数组一样高效。对于 hash 段的值,查找几乎就是计算 hash 值的过程(其中string 的 hash 值是事先计算好保存的),只有在碰撞的时候才会有少许的额外查找时间,而空间也不至于过于浪费。在 hash 表比较满时,插入较容易发生碰撞,这个时候,则需要在表中找到空的插槽。lua 在table 的结构中记录了一个指针顺次从一头向另一头循序插入来解决空槽的检索。每个槽点在记录 next 指针保存被碰撞的 key 的关联性。
整个来说,这种解决方法是非常不错的。
---上点例子
t={ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,6}for i=1,20 do t[i]=nil table.insert(t,20)endfor i=1,30 do print(t[i])end得出的结果:20202020nilnilnilnilnilnilnilnilnilnilnilnilnilnilnilnil111162020202020
---再来一段:
for startIndex = 1,10 do t = {} for j = startIndex, 15 do t[j] = j end table.insert(t,"InsertedValue") tableStr = "" for i = 1,16 do if t[i] == nil then tableStr = tableStr .."nil" .." | " else tableStr = tableStr ..t[i] .." | " end end print("StartIndex = "..startIndex..", The Table = " .. tableStr)end---[/i][/i][i][i]StartIndex = 1, The Table = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | InsertedValue | StartIndex = 2, The Table = nil | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | InsertedValue | StartIndex = 3, The Table = nil | nil | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | InsertedValue | StartIndex = 4, The Table = nil | nil | nil | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | InsertedValue | StartIndex = 5, The Table = nil | nil | nil | nil | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | InsertedValue | StartIndex = 6, The Table = nil | nil | nil | nil | nil | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | InsertedValue | StartIndex = 7, The Table = nil | nil | nil | nil | nil | nil | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | InsertedValue | StartIndex = 8, The Table = InsertedValue | nil | nil | nil | nil | nil | nil | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | nil | StartIndex = 9, The Table = InsertedValue | nil | nil | nil | nil | nil | nil | nil | 9 | 10 | 11 | 12 | 13 | 14 | 15 | nil | StartIndex = 10, The Table = InsertedValue | nil | nil | nil | nil | nil | nil | nil | nil | 10 | 11 | 12 | 13 | 14 | 15 | nil | [/i][/i][i][i]