2016-07-13 29 views
2

Ich musste wissen, welche Methode die schnellere ist, weil ich Elemente in einer Tabelle in einem Projekt einfügen muss, wo Leistung wichtig ist. Ich habe das folgende Stück Code ausführen:Warum ist t [#t + 1] = e schneller als table.insert (t, e)?

local total = 0 

local mytable = {} 

for i = 1, 1e7 do 
    local clock = os.clock 
    local push = table.insert 
    local t = clock() 

    push(mytable, 0) 

    t = clock() - t 
    total = total + t 
end 

print("table.insert: "..total) 

local total = 0 

local mytable = {} 

for i = 1, 1e7 do 
    local clock = os.clock 
    local t = clock() 

    mytable[#mytable + 1] = 0 

    t = clock() - t 
    total = total + t 
end 

print("Manual approach: "..total) 

Und es stellt sich heraus, dass das zweite Verfahren etwa 2 Sekunden schneller als der erste läuft.

Ich verstehe, dass der erste ist ein Funktionsaufruf, aber im Gegensatz dazu ruft der zweite den -Operator, tut eine Addition und weist dann einen Index zu einem Wert, alle auf der Lua-Seite, wo der erste tut es auf der C-Seite.

Warum ist die zweite Methode schneller? Sind Funktionen wirklich so langsam?

+3

'i = i + 1; t [i] = e' ist noch schneller –

+5

Verschieben Sie die Uhr Sachen und 'local push = table.insert' außerhalb der Schleifen. So messen Sie wahrscheinlich den Zugriff auf globale Variablen. Das Ganze wird für mich ungefähr 3 mal so schnell. Und ich bekomme 7% Unterschied zwischen den beiden Ansätzen. – lhf

+1

@Egor Skriptunoff meinst du, ich sollte eine Variable behalten, die die Länge der Tabelle enthält? – user6245072

Antwort

0

Da Funktionsaufruf. nächsten Code anzeigen. Dieser Code basiert auf Ihrem Code.

function insert(t, v) 
    t[#t + 1] = v 
end 

for i = 1, 1e7 do 
    local clock = os.clock 
    local t = clock() 

    --mytable[#mytable + 1] = 0 
    insert(mytable, 0) 

    t = clock() - t 
    total = total + t 
end 

Code funktioniert gleich, aber erhöhen auf einen Funktionsaufruf.

Ergebnis Es ist table.insert: 4,705

Handbuch Ansatz: 4,752 < - Insert-Funktion