Optimising literals away

MRAB python at mrabarnett.plus.com
Wed Sep 1 00:38:26 CEST 2010

On 31/08/2010 23:11, Cameron Simpson wrote:
> On 31Aug2010 22:53, MRAB<python at mrabarnett.plus.com>  wrote:
> [...]
> |>>>def m(arg):
> |>>>if arg&  set([1,2,3]):
> |>
> |>set() is a function call, not a literal. When m is called, who knows
> |>what 'set' will be bound to? In Py3, at least, you could write {1,2,3},
> |>which is much faster as it avoids creating and deleting a list. On my
> |>machine, .35 versus .88 usec. Even then, it must be calculated each time
> |>because sets are mutable and could be returned to the calling code.
> |>
> | There's still the possibility of some optimisation. If the resulting
> | set is never stored anywhere (bound to a name, for example) then it
> | could be created once. When the expression is evaluated there could be
> | a check so see whether 'set' is bound to the built-in class, and, if it
> | is, then just use the pre-created set.
> Wouldn't you need to repeat that check every time, otherwise "set" may
> no longer be the builtin?

Isn't that what I said?

My point is that if you have a set of constants which is created and
then discarded you can cache it and reuse it next time. You check every
time whether 'set' is bound to the set class.

More information about the Python-list mailing list