[Python-ideas] More compact bytecode

Victor Stinner victor.stinner at gmail.com
Fri Feb 5 18:30:09 EST 2016


2016-02-05 23:46 GMT+01:00 Yury Selivanov <yselivanov.ml at gmail.com>:
> What do you think about turning constant slice objects into actual
> constants?

It doesn't look interesting.

bench$ python3 -m timeit -s 'def f(list):' -s ' list[:1]; list[:1];
list[:1]; list[:1]; list[:1]' -s 'l=list("hello")' 'f(l)'
1000000 loops, best of 3: 1.34 usec per loop

bench$ python3 -m timeit -s 'def f(list):' -s ' list["whatever"];
list["whatever"]; list["whatever"]; list["whatever"];
list["whatever"]' -s 'import types; co=f.__code__; consts=[slice(0, 1,
None) if const == "whatever" else const for const in co.co_consts];
f.__code__ = types.CodeType(co.co_argcount, co.co_kwonlyargcount,
co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code,
tuple(consts), co.co_names, co.co_varnames, co.co_filename,
co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars,
co.co_cellvars); l=list("hello")' 'f(l)'
1000000 loops, best of 3: 1.3 usec per loop

It's only 3% faster on a microbenchmark.

(On my laptop: 687 ns => 658 ns: 4% faster)

I'm not sure that the benchmark is "fair" since the slice object has a
free list of 1 item which is probably always used in this benchmark.

But you will be able to easily implement suck "hack" in fatoptimizer
which already has similar optimizations.

IMHO it's ok for an optimizer like fatoptimizer, it's not worth for
the default builtin optimizer in CPython.

Victor


More information about the Python-ideas mailing list