Geschwindigkeitstest - zwei Arten des for loops über tuples

Ich habe getestet, ob es einen Geschwindigkeitsunterschied zwischen zwei Arten des for loops über eine Liste von tuples gibt:

liste_von_tuples = [(1, 2), (3, 4), (5, 6)]

Es gibt 100.000 tuple, und jeder tuple enthält 2 Zufallszahlen.

Art 1:

for i in liste_von_tuples: 
   res.append(i[1])

Art 2:

for i, j in liste_von_tuples: 
   res.append(j)

Ich hatte erwartet, dass die zweite Art schneller ist, da bei Art 1 eine Zuweisungsoperation von zwei Werten und danach eine Auswahloperation und eine Zuweisungsoperation nötig sind, während bei Art 2 die Auswahloperation wegfällt.

Der Test bestätigte meine Ansicht.

Art 1 braucht bei der Liste mit 100.000 Tuples von je 2 Zufallszahlen zwischen 4% und 12% länger.

Fazit: Bei for loops über tuple, sollte Art 2 verwendet werden:

for i, j in liste_von_tuples: 
   res.append(j)

Die verwendete und ausführlich kommentierte Testdatei ist angehängt.

Anmerkung: Meine Python Tests können jetzt auch mit Mercurial heruntergeladen werden: http://bitbucket.org/ArneBab/python_tests/

Ideen und Patches wären cool :)

AnhangGröße
for-loops-geschwindigkeitstest.py5.57 KB

Use Node:

⚙ Babcom is trying to load the comments ⚙

This textbox will disappear when the comments have been loaded.

If the box below shows an error-page, you need to install Freenet with the Sone-Plugin or set the node-path to your freenet node and click the Reload Comments button (or return).

If you see something like Invalid key: java.net.MalformedURLException: There is no @ in that URI! (Sone/search.html), you need to setup Sone and the Web of Trust

If you had Javascript enabled, you would see comments for this page instead of the Sone page of the sites author.

Note: To make a comment which isn’t a reply visible to others here, include a link to this site somewhere in the text of your comment. It will then show up here. To ensure that I get notified of your comment, also include my Sone-ID.

Link to this site and my Sone ID: sone://6~ZDYdvAgMoUfG6M5Kwi7SQqyS-gTcyFeaNN1Pf3FvY

This spam-resistant comment-field is made with babcom.

Inhalt abgleichen
Willkommen im Weltenwald!
((λ()'Dr.ArneBab))



Beliebte Inhalte

Draketo neu: Beiträge

Ein Würfel System

sn.1w6.org news