What's the difference between a list comprehension, and calling list on a generator expression? (By the way, everything below applies to set comprehensions and, with trivial tweaks, dict comprehensions, but I'm only going to talk about lists for simplicity.)

To be concrete, what's the difference between:

    [x for x in it]
    list(x for x in it)

As it turns out, they behave exactly the same way except for two differences. (In Python 3.0-3.4; there were more differences in 2.x.)

StopIteration

First, if you raise StopIteration anywhere inside (in the main loop clause, any additional clauses, or the expression), the former will pass the exception straight through, while the latter will eat it and end early. So, for example:

    >>> def stop(): raise StopIteration
    >>> a = [x for x in (1, 0) if x or stop()]
    StopIteration:
    >>> a
    NameError: name 'a' is not defined
    >>> a = list(x for x in (1, 0) if x or stop())
    >>> a
    [1]

It would be nice to be able to make them behave _exactly_ the same way. That would simplify the language--no more need to define two very similar concepts independently; you can just define comprehensions as if calling list on the equivalent generator expression.

Performance

The list(genexpr) version is up to 40% slower than the comprehension. That isn't acceptable. The benefit of simplifying the language (and, as a minor side benefit, being able to StopIteration a listcomp) isn't worth that cost.
So, is there a way to optimize that?

Implementation

Before we try to optimize the bytecode, we have to know what it looks like.
Let's take a trivial comprehension, [i for i in x] (where x is a local). This is obviously a silly thing to write, but not having anything extra to get in the way will make the bytecode easier to read.

The comprehension looks like this:

    LOAD_CONST 
    LOAD_CONST ""
    MAKE_FUNCTION 0
    LOAD_NAME x
    GET_ITER
    CALL_FUNCTION 1

And a equivalent genexpr is pretty much identical:

    LOAD_CONST 
    LOAD_CONST ""
    MAKE_FUNCTION 0
    LOAD_NAME x
    GET_ITER
    CALL_FUNCTION 1

That's not very interesting--it just gets some magic bytecode from somewhere, makes a function out of it, calls it with iter(x), and returns the value! What does that magic function look like? For the comprehension:

    BUILD_LIST
    LOAD_FAST .0
    :loop
    FOR_ITER :endloop
    LIST_APPEND 1
    JUMP_ABSOLUTE :loop
    :endloop
    RETURN_VALUE

(Actually, a real listcomp will STORE_VALUE i and LOAD_VALUE i before the LIST_APPEND, because Python has no way of knowing that the expression on i happens to always have the same value as i, but I stripped that for simplicity.)

And for the genexpr:

    LOAD_FAST .0
    :loop
    FOR_ITER :endloop
    YIELD_VALUE 1
    POP_TOP
    JUMP_ABSOLUTE :loop
    :endloop
    LOAD_CONST None
    RETURN_VALUE

So, the only differences are that there's no BUILD_LIST, it YIELDs and POPs each value instead of LIST_APPENDing it, and it returns None instead of the list.

As you can guess, calling list on the genexpr looks like this:

    LOAD_NAME list
    LOAD_CONST 
    LOAD_CONST ""
    MAKE_FUNCTION 0
    LOAD_NAME x
    GET_ITER
    CALL_FUNCTION 1
    CALL_FUNCTION 1

In other words, it's just list(genexpr-function(iter(x)))

Handling StopIteration in listcomp-code

If the only difference between [listcomp] and list(genexpr) is that the latter handles StopIteration, there's a pretty obvious way to make them act the same without the 40% performance hit: just make listcomp handle StopIteration.

In pseudo-Python, the current listcomp-code looks like this:

    a = []
    for i in x:
        a.append(i)
    return a

And we want this:

    a = []
    try:
        for i in x:
            a.append(i)
    except StopIteration:
        pass
    return a

Let's translate that into bytecode:

    BUILD_LIST
    SETUP_EXCEPT :except
    LOAD_FAST .0
    :loop
    FOR_ITER :endloop
    LIST_APPEND 1
    JUMP_ABSOLUTE :loop
    :except
    DUP_TOP
    LOAD_GLOBAL StopIteration
    COMPARE_OP exception_match
    POP_JUMP_IF_FALSE :raise
    POP_TOP
    POP_TOP
    POP_TOP
    POP_EXCEPT
    JUMP_FORWARD :endloop
    :raise
    END_FINALLY
    :endloop
    RETURN_VALUE

I cheated a bit by merging endloop and endexcept into one. Normally, Python would compile this so the FOR_ITER jumped to a JUMP_FORWARD that jumped to the actual ending, but when we're handing-coding (or writing new special-case compiler code) there's no reason to do that.

Of course in real life you wouldn't want to LOAD_GLOBAL StopIteration, but this gets the idea across.

So, how much slower is this?

Well, there's no per-iteration cost, because the code inside the loop is the same as ever.

There is a tiny bit of constant overhead from the SETUP_EXCEPT. It's around 12ns on a machine where a simple listcomp takes around 500ns + 100ns/iteration. So, we're talking under 1% overhead for most cases. There's also probably some cost from loading a larger function and jumping a bit farther, although I haven't been able to measure it.

If you actually raise StopIteration, or course, that slows things down by maybe 250ns, but since that didn't work before, you can't complain that it's slower.

If you raise anything else, it also adds a similar amount of time (a bit harder to measure), but I don't think anyone cares about the performance of list comprehensions that fail by raising.

Meanwhile, the required changes to CPython are all in one function in compile.c, and not very complicated.

If we were willing to add a new opcode, we could add a SETUP_STOP_ITERATION, which jumps on StopIteration and ignores any other exception. Then we only need one new line in the code:

    BUILD_LIST
    LOAD_FAST .0
    SETUP_STOP_ITERATION
    :loop
    FOR_ITER :endloop
    LIST_APPEND 1
    JUMP_ABSOLUTE :loop
    :endloop
    RETURN_VALUE

This obviously make the compiler simpler, but it does so at the cost of a new bytecode, which really just moves the complexity somewhere else--and somewhere less desirable. (Adding a new bytecode is a bigger change than just changing the compiler to compile different bytecode.) And it wouldn't be any faster for the typical fast path (no exceptions). It might be a little faster when exceptions are raised, and it does save a few bytes in the compiled bytecode, but I don't think that's worth it.

Optimizing list(genexpr)

If we're going to simplify the language, wouldn't it be nice to also simplify the implementation? Can't we get rid of the code to build magic listcomp functions, and maybe even the special BUILD_LIST and LIST_APPEND opcodes?

We need to know why it's 40% slower before we can fix it. It's not because of the call to list. In fact, we can inline the list building:

    LOAD_CONST 
    LOAD_CONST ""
    MAKE_FUNCTION 0
    LOAD_NAME x
    GET_ITER
    CALL_FUNCTION 1
    BUILD_LIST
    :loop
    FOR_ITER :endloop
    LIST_APPEND 2
    JUMP_ABSOLUTE :loop
    :endloop

This shaves off a few nanoseconds of constant cost and a few nanoseconds per iteration, but doesn't make much of a dent in the 40%.

The real cost here is we have to go back and forth between the FOR_ITER and the inner function's YIELD once per iteration. In other words, we're doing a generator suspend and resume for each iteration.

So, what we need is some new FAST_FOR_ITER and FAST_YIELD that can trade off within the same function. And we'll also need a FAST_RETURN, of course.

So, FAST_FOR_ITER has to jump to the inlined generator. It has nowhere to put an extra operand, but that's fine; since it doesn't ever directly run its own outer body, we can just put the inlined generator right after it. Next, FAST_YIELD has to jump to the outer loop body. Then, the outer loop body has to jump to the line after FAST_YIELD, instead of all the way back to the FAST_FOR_ITER. The inner loop has to jump to the outer FAST_FOR_ITER instead of its own FOR_ITER:

    BUILD_LIST
    LOAD_FAST .0
    :outerloop
    FAST_FOR_ITER :outerendloop
    FOR_ITER :innerendloop
    FAST_YIELD :outerbody
    :innercontinue
    POP_TOP
    JUMP_ABSOLUTE :outerloop
    :innerendloop
    LOAD_CONST None
    FAST_RETURN :outerloop
    :outerbody
    LIST_APPEND 1
    JUMP_ABSOLUTE :innercontinue
    :outerendloop
    RETURN_VALUE

What exactly is FAST_FOR_ITER doing here? It's not really iterating anything; it just jumps to :outerendloop if you've raised StopIteration or called FAST_RETURN, and falls through to the next line otherwise.

I'm not sure how it can even know whether it's gotten here as a result of a FAST_RETURN, or a FAST_YIELD that's been processed inline... but as it turns out, we can just optimize out the FAST_RETURN, because all we're ever going to do is ignore what we got and jump to :outerendloop. So it doesn't really matter how we'd implement it; let's just replace it with a JUMP_FORWARD to :outerendloop.

    BUILD_LIST
    LOAD_FAST .0
    :outerloop
    FAST_FOR_ITER :outerendloop
    FOR_ITER :innerendloop
    FAST_YIELD :outerbody
    :innercontinue
    POP_TOP
    JUMP_ABSOLUTE :outerloop
    :innerendloop
    JUMP_FORWARD :outerendloop
    :outerbody
    LIST_APPEND 1
    JUMP_ABSOLUTE :innercontinue
    :outerendloop
    RETURN_VALUE

But now, what exactly is FAST_YIELD doing? Basically it's just doing a DUP_TOP and a JUMP_RELATIVE. And we don't need the DUP_TOP, because we don't actually need the value after we jump back here--all we do is POP_TOP it. So:

    BUILD_LIST
    LOAD_FAST .0
    :outerloop
    FAST_FOR_ITER :outerendloop
    FOR_ITER :innerendloop
    JUMP_FORWARD :outerbody
    :innercontinue
    JUMP_ABSOLUTE :outerloop
    :innerendloop
    JUMP_FORWARD :outerendloop
    :outerbody
    LIST_APPEND 1
    JUMP_ABSOLUTE :innercontinue
    :outerendloop
    RETURN_VALUE

Now we've got all these lines that just jump to other jumps, so we can optimize them all out:

    BUILD_LIST
    LOAD_FAST .0
    :loop
    FAST_FOR_ITER :endloop
    FOR_ITER :endloop
    LIST_APPEND 1
    JUMP_ABSOLUTE :endloop
    :outerendloop
    RETURN_VALUE

And now, this is identical to the original listcomp code, except for that outer FAST_FOR_ITER opcode.

And what exactly is it doing? Basically, if you've raised StopIteration it jumps to :outerendloop. But there's no need to ever jump back to it for it to serve that purpose; it can work just like SETUP_EXCEPT. In fact, it's exactly the same as the SETUP_STOP_ITERATION above. So, let's replace it, and move the jump:

    BUILD_LIST
    LOAD_FAST .0
    SETUP_STOP_ITERATION :endloop
    :loop
    FOR_ITER :endloop
    LIST_APPEND 1
    JUMP_ABSOLUTE :loop
    :endloop
    RETURN_VALUE

And that's exactly the same code we had for adding StopIteration handling to [listcomp].
So, yes, you can inline and optimize list(genexpr), but the result is exactly the same as adding StopIteration handling to [listcomp].
0

Add a comment

Hybrid Programming
Hybrid Programming
5
Greenlets vs. explicit coroutines
Greenlets vs. explicit coroutines
6
ABCs: What are they good for?
ABCs: What are they good for?
1
A standard assembly format for Python bytecode
A standard assembly format for Python bytecode
6
Unified call syntax
Unified call syntax
8
Why heapq isn't a type
Why heapq isn't a type
1
Unpacked Bytecode
Unpacked Bytecode
3
Everything is dynamic
Everything is dynamic
1
Wordcode
Wordcode
1
For-each loops should define a new variable
For-each loops should define a new variable
4
Views instead of iterators
Views instead of iterators
2
How lookup _could_ work
How lookup _could_ work
2
How lookup works
How lookup works
7
How functions work
How functions work
2
Why you can't have exact decimal math
Why you can't have exact decimal math
2
Can you customize method resolution order?
Can you customize method resolution order?
1
Prototype inheritance is inheritance
Prototype inheritance is inheritance
1
Pattern matching again
Pattern matching again
The best collections library design?
The best collections library design?
1
Leaks into the Enclosing Scope
Leaks into the Enclosing Scope
2
Iterable Terminology
Iterable Terminology
8
Creating a new sequence type is easy
Creating a new sequence type is easy
2
Going faster with NumPy
Going faster with NumPy
2
Why isn't asyncio too slow?
Why isn't asyncio too slow?
Hacking Python without hacking Python
Hacking Python without hacking Python
1
How to detect a valid integer literal
How to detect a valid integer literal
2
Operator sectioning for Python
Operator sectioning for Python
1
If you don't like exceptions, you don't like Python
If you don't like exceptions, you don't like Python
2
Spam, spam, spam, gouda, spam, and tulips
Spam, spam, spam, gouda, spam, and tulips
And now for something completely stupid…
And now for something completely stupid…
How not to overuse lambda
How not to overuse lambda
1
Why following idioms matters
Why following idioms matters
1
Cloning generators
Cloning generators
5
What belongs in the stdlib?
What belongs in the stdlib?
3
Augmented Assignments (a += b)
Augmented Assignments (a += b)
11
Statements and Expressions
Statements and Expressions
3
An Abbreviated Table of binary64 Values
An Abbreviated Table of binary64 Values
1
IEEE Floats and Python
IEEE Floats and Python
Subtyping and Ducks
Subtyping and Ducks
1
Greenlets, threads, and processes
Greenlets, threads, and processes
6
Why don't you want getters and setters?
Why don't you want getters and setters?
8
The (Updated) Truth About Unicode in Python
The (Updated) Truth About Unicode in Python
1
How do I make a recursive function iterative?
How do I make a recursive function iterative?
1
Sockets and multiprocessing
Sockets and multiprocessing
Micro-optimization and Python
Micro-optimization and Python
3
Why does my 100MB file take 1GB of memory?
Why does my 100MB file take 1GB of memory?
1
How to edit a file in-place
How to edit a file in-place
ADTs for Python
ADTs for Python
5
A pattern-matching case statement for Python
A pattern-matching case statement for Python
2
How strongly typed is Python?
How strongly typed is Python?
How do comprehensions work?
How do comprehensions work?
1
Reverse dictionary lookup and more, on beyond z
Reverse dictionary lookup and more, on beyond z
2
How to handle exceptions
How to handle exceptions
2
Three ways to read files
Three ways to read files
2
Lazy Python lists
Lazy Python lists
2
Lazy cons lists
Lazy cons lists
1
Lazy tuple unpacking
Lazy tuple unpacking
3
Getting atomic writes right
Getting atomic writes right
Suites, scopes, and lifetimes
Suites, scopes, and lifetimes
1
Swift-style map and filter views
Swift-style map and filter views
1
Inline (bytecode) assembly
Inline (bytecode) assembly
Why Python (or any decent language) doesn't need blocks
Why Python (or any decent language) doesn't need blocks
18
SortedContainers
SortedContainers
1
Fixing lambda
Fixing lambda
2
Arguments and parameters, under the covers
Arguments and parameters, under the covers
pip, extension modules, and distro packages
pip, extension modules, and distro packages
Python doesn't have encapsulation?
Python doesn't have encapsulation?
3
Grouping into runs of adjacent values
Grouping into runs of adjacent values
dbm: not just for Unix
dbm: not just for Unix
How to use your self
How to use your self
1
Tkinter validation
Tkinter validation
7
What's the deal with ttk.Frame.__init__(self, parent)
What's the deal with ttk.Frame.__init__(self, parent)
1
Does Python pass by value, or by reference?
Does Python pass by value, or by reference?
9
"if not exists" definitions
"if not exists" definitions
repr + eval = bad idea
repr + eval = bad idea
1
Solving callbacks for Python GUIs
Solving callbacks for Python GUIs
Why your GUI app freezes
Why your GUI app freezes
21
Using python.org binary installations with Xcode 5
Using python.org binary installations with Xcode 5
defaultdict vs. setdefault
defaultdict vs. setdefault
1
Lazy restartable iteration
Lazy restartable iteration
2
Arguments and parameters
Arguments and parameters
3
How grouper works
How grouper works
1
Comprehensions vs. map
Comprehensions vs. map
2
Basic thread pools
Basic thread pools
Sorted collections in the stdlib
Sorted collections in the stdlib
4
Mac environment variables
Mac environment variables
Syntactic takewhile?
Syntactic takewhile?
4
Can you optimize list(genexp)
Can you optimize list(genexp)
MISRA-C and Python
MISRA-C and Python
1
How to split your program in two
How to split your program in two
How methods work
How methods work
3
readlines considered silly
readlines considered silly
6
Comprehensions for dummies
Comprehensions for dummies
Sockets are byte streams, not message streams
Sockets are byte streams, not message streams
9
Why you don't want to dynamically create variables
Why you don't want to dynamically create variables
7
Why eval/exec is bad
Why eval/exec is bad
Iterator Pipelines
Iterator Pipelines
2
Why are non-mutating algorithms simpler to write in Python?
Why are non-mutating algorithms simpler to write in Python?
2
Sticking with Apple's Python 2.7
Sticking with Apple's Python 2.7
Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.