Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7091177
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T08:09:06+00:00 2026-05-28T08:09:06+00:00

I’m encountering what seems like quite surprising performance differences when iterating over a small

  • 0

I’m encountering what seems like quite surprising performance differences when iterating over a small container with a custom iterator. I was hoping someone might be able to help me understand where these differences are coming from.

First some context; I’m writing a number of python extension modules using boost::python, one of which contains a binding to a 3d float vector type that implements getitem. Since it has getitem its possible to iterate over it, however it seems quite slow, but its not obvious why so I decided to play around with some simple custom iterators in python to get a better idea of how things work. Which is where these iterators came from…

class MyIterator1(object):
    __slots__ = ['values', 'popfn']

    def __init__(self):
        self.values = ['x', 'y', 'z']
        self.popfn = self.values.pop

    def __length_hint__(self):
        return 3

    def __iter__(self):
        return self

    def next(self):
        try:
            return self.popfn()
        except IndexError:
            raise StopIteration

class MyIterator2(object):
    __slots__ = ['values', 'itfn']

    def __init__(self):
        self.values = ['x', 'y', 'z']
        it = iter(self.values)
        self.itfn = it.next

    def __length_hint__(self):
        return 3

    def __iter__(self):
        return self

    def next(self):
        return self.itfn()

class MyIterator3(object):
    __slots__ = ['values', 'i']

    def __init__(self):
        self.values = ['x', 'y', 'z']
        self.i = 0

    def __length_hint__(self):
        return 3

    def __iter__(self):
        return self

    def next(self):
        if self.i >= 3:
            raise StopIteration
        value = self.values[self.i]
        self.i += 1
        return value

def MyIterator4():
    val = ['x', 'y', 'z']
    yield val[0]
    yield val[1]
    yield val[2]

Next I ran these through a script with the timeit module (which assumes the above code is in a module called testiter)

import timeit

timer1 = timeit.Timer('r = list(testiter.MyIterator1())', 'import testiter')
timer2 = timeit.Timer('r = list(testiter.MyIterator2())', 'import testiter')
timer3 = timeit.Timer('r = list(testiter.MyIterator3())', 'import testiter')
timer4 = timeit.Timer('r = list(testiter.MyIterator4())', 'import testiter')
timer5 = timeit.Timer('r = list(iter(["x", "y", "z"]))', 'import testiter')

print 'list(testiter.MyIterator1())'
print timer1.timeit()

print "\n"

print 'list(testiter.MyIterator2())'
print timer2.timeit()

print "\n"

print 'list(testiter.MyIterator3())'
print timer3.timeit()

print "\n"

print 'list(testiter.MyIterator4())'
print timer4.timeit()

print "\n"

print 'list(iter(["x", "y", "z"]))'
print timer5.timeit()

This prints out the following

list(testiter.MyIterator1())
8.57359290123


list(testiter.MyIterator2())
5.28959393501


list(testiter.MyIterator3())
6.11230111122


list(testiter.MyIterator4())
2.31263613701


list(iter(["x", "y", "z"]))
1.26243281364

Unsurprisingly the python listiterator is the fastest, by quite a margin. I assume this is down to some magic optimisations within python. The generator is also considerably faster than the MyIterator classes, which again I’m not hugely surprised about, and assume is due to all the work being done in c, however thats just a guess. Now the others are more confusing/supprising. Are try/except statements as expensive as they seem in this context or is something else going on ?

Any help in explaining these differences would be greatly appreciated! Apologies for the long post.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T08:09:07+00:00Added an answer on May 28, 2026 at 8:09 am

    A few ideas off the top of my head; sorry if they’re not palpable enough:

    • The first iterator is using the list’s pop to implement next, meaning the list is mutated after each element is retrieved. Perhaps this mutation of a dynamically allocated composite data structure is reducing performance. All depends on the implementation details of lists, so this could be completely irrelevant.
    • The last iterator is using a feature wired into the language (yield) in a simple context to produce the result. At a guess, I’ll say this indicates there’s more room for optimisation than a custom iterator class attempting to achieve the same result.
    • The 5th timer isn’t using a custom iterator, and is instead using the one provided for lists directly. Iterators for lists are probably well-optimized, and there isn’t a layer of indirection that those custom classes use, some of which are using such a list iterator internally anyway.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text
I used javascript for loading a picture on my website depending on which small
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have some data like this: 1 2 3 4 5 9 2 6
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.