Speed example (tinsert is slooow)
No edit summary |
(Speed example (tinsert is slooow)) |
||
| Line 1: | Line 1: | ||
{{:Lua/Libshortcut|tinsert|table.insert}} | |||
From [http://lua-users.org/wiki/TableLibraryTutorial TableLibraryTutorial] of lua-users.org. | From [http://lua-users.org/wiki/TableLibraryTutorial TableLibraryTutorial] of lua-users.org. | ||
| Line 47: | Line 48: | ||
n 11 | n 11 | ||
---- | |||
{{ | |||
== Speed == | |||
If you are appending to an integer-indexed table, it is always faster to track the size yourself, as this example demonstrates (clocked on a 3Ghz P4) | |||
local t = {} | |||
local tinsert=table.insert | |||
local b = os.clock() | |||
local n=1 | |||
t.n=1 | |||
for i=1,5e6 do | |||
table.insert(t, "") -- 2.25s - extra cost of looking up table. subkeys | |||
tinsert(t, "") -- 2.02s - local function call is slightly faster | |||
t[#t+1] = "" -- 1.72s - a lot of the cost seems to be #t | |||
local tn=t.n; t[tn]=""; t.n=tn+1 -- 1.19s - storing "n" in the table | |||
t[n]="";n=n+1 -- 0.88s - storing "n" in a local | |||
t[i]="" -- 0.78s - cheat, we don't have "i" usually | |||
-- empty -- 0.08s overhead for the loop | |||
end | |||
local e = os.clock() | |||
print(e-b) | |||
== See Also == | |||
* [[tinsertbeforeval]] | |||
{{LUA}} | |||