Skip to content

Minor performance improvement to ilen() #230

@achampion

Description

@achampion

Feel free to ignore.
A potential minor performance improvement for ilen() for Py3 by using zip() with a itertools.count() vs. enumerate():

import itertools
from collections import deque

def ilen(iterable):
    counter = itertools.count()
    deque(zip(iterable, counter), maxlen=0)
    return next(counter)

Note you have a recipe for consume() so this could be:

def ilen(iterable):
    counter = itertools.count()
    consume(zip(iterable, counter))
    return next(counter)

In []:
import more_itertools as mit
%timeit mit.ilen(x for x in range(10000000) if x % 3 == 0)

Out[]:
860 ms ± 14.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In []:
%timeit ilen(x for x in range(10000000) if x % 3 == 0)

Out[]:
786 ms ± 8.24 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

This performance improvement seems stable for various orders of magnitude, except very small <10 where the overhead of the extra function calls outweighs any performance improvement.

Note: tested on Py2 and it was unfortunately slower (with xrange()). Perhaps one to save when Py2 goes away.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions