[Python-Dev] Do more at compile time; less at runtime
MRAB
python at mrabarnett.plus.com
Mon Dec 10 00:29:16 CET 2012
On 2012-12-09 22:22, Mark Shannon wrote:
> Hi all,
>
> The current CPython bytecode interpreter is rather more complex than it
> needs to be. A number of bytecodes could be eliminated and a few more
> simplified by moving the work involved in handling compound statements
> (loops, try-blocks, etc) from the interpreter to the compiler.
>
> This simplest example of this is the while loop...
> while cond:
> body
>
> This currently compiled as
>
> start:
> if not cond goto end
> body
> goto start
> end:
>
> but it could be compiled as
>
> goto test:
> start:
> body
> if cond goto start
>
> which eliminates one instruction per iteration.
>
> A more complex example is a return in a try-finally block.
>
> try:
> part1
> if cond:
> return X
> part2
> finally:
> part3
>
> Currently, handling the return is complex and involves "pseudo
> exceptions", but if part3 were duplicated by the compiler, then the
> RETURN bytecode could just perform a simple return.
> The code above would be compiled thus...
>
> PUSH_BLOCK try
> part1
> if not X goto endif
> push X
> POP_BLOCK
> part3 <<< duplicated
> RETURN_VALUE
> endif:
> part2
> POP_BLOCK
> part3 <<< duplicated
>
> The changes I am proposing are:
>
[snip]
Is it necessary to duplicate part3? Is it possible to put it into a
subroutine if it's long? (And I do mean a simple cheap subroutine.)
More information about the Python-Dev
mailing list