Searching for patterns on the screen
Paul McGuire
ptmcg at austin.rr._bogus_.com
Fri Sep 15 15:38:39 EDT 2006
"John Machin" <sjmachin at lexicon.net> wrote in message
news:1158333401.286945.147870 at b28g2000cwb.googlegroups.com...
>
> Paul McGuire wrote:
>> "Jerry Hill" <malaclypse2 at gmail.com> wrote in message
>> news:mailman.125.1158327884.10491.python-list at python.org...
>> > Hello all,
>> As far as working just in Python, you could remove the tuple unpacking
>> inside removeColor, and shorten it to just:
>>
>> def removeColor(rgb):
>> return rgb==(0,0,0)
>>
>> or even better:
>>
>> BLACK = (0,0,0)
>> def removeColor(rgb):
>> return rgb==BLACK
>>
>> By defining BLACK once and just referring to it by name, you also avoid
>> dynamically constructing the (0,0,0) tuple in every call.
>
> Bzzzzzt. It's not dynamically constructed. Its a constant (in 2.4 at
> least)
>
> | >>> BLACK=(0,0,0)
> | >>> def func1(rgb):
> | ... return rgb==BLACK
> | ...
> | >>> def func2(rgb):
> | ... return rgb==(0,0,0)
> | ...
> | >>> import dis
> | >>> dis.dis(func1)
> | 2 0 LOAD_FAST 0 (rgb)
> | 3 LOAD_GLOBAL 1 (BLACK)
> | 6 COMPARE_OP 2 (==)
> | 9 RETURN_VALUE
> | >>> dis.dis(func2)
> | 2 0 LOAD_FAST 0 (rgb)
> | 3 LOAD_CONST 2 ((0, 0, 0))
> | 6 COMPARE_OP 2 (==)
> | 9 RETURN_VALUE
> | >>>
>
>
> C:\junk>python -mtimeit -s"BLACK=(0,0,0);rgb=(1,1,1)" "rgb==BLACK"
> 1000000 loops, best of 3: 0.129 usec per loop
>
> C:\junk>python -mtimeit -s"rgb=(1,1,1)" "rgb==(0,0,0)"
> 1000000 loops, best of 3: 0.127 usec per loop
>
Hunh! It sure seems like I recently had to do something like this, and the
value was rebuilt every time. Perhaps I was building a "constant" list
instead of a tuple...
>>> def fn(lst):
... return lst == [1,1,1]
...
>>> import dis
>>> dis.dis(fn)
2 0 LOAD_FAST 0 (lst)
3 LOAD_CONST 1 (1)
6 LOAD_CONST 1 (1)
9 LOAD_CONST 1 (1)
12 BUILD_LIST 3
15 COMPARE_OP 2 (==)
18 RETURN_VALUE
>>>
So tuples can be inlined as constants, but lists will be built on the fly.
-- Paul
More information about the Python-list
mailing list