do .. while loops ?
Mirko Liss
mirko.liss at web.de
Sun Jul 15 04:58:01 EDT 2001
On Sat, 14 Jul 2001, Erik Max Francis wrote:
> do...while loops are a language feature that tend to be fairly
> controversial in some languages, for some reason -- probably because it
> seems more on the "fluff" side to many people. They're easy enough to
> simulate with other control structures.
On the other hand, if you write do..while - loops, you can get rid
of one jump per iteration. Rewriting while - loops into
do ... while - loops is a common optimization.
Lets take a look at it:
Python 1.5.2 (#1, Jul 29 2000, 14:28:37) [GCC 2.95.2 19991024 (release)]
on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import dis
>>> def testme(a):
... while a > 0:
... a = a -1
...
>>> dis.dis(testme)
0 SET_LINENO 1
3 SET_LINENO 2
6 SETUP_LOOP 34 (to 43)
>> 9 SET_LINENO 2
12 LOAD_FAST 0 (a)
15 LOAD_CONST 1 (0)
18 COMPARE_OP 4 (>)
21 JUMP_IF_FALSE 17 (to 41)
24 POP_TOP
25 SET_LINENO 3
28 LOAD_FAST 0 (a)
31 LOAD_CONST 2 (1)
34 BINARY_SUBTRACT
35 STORE_FAST 0 (a)
38 JUMP_ABSOLUTE 9
>> 41 POP_TOP
42 POP_BLOCK
>> 43 LOAD_CONST 0 (None)
46 RETURN_VALUE
>>>
Rewriting this to
>>> def testme2(a):
... while 1:
... a = a - 1
... if a < 0 : break
...
yields something like:
...
35 LOAD_FAST 0 (a)
38 LOAD_CONST 2 (0)
41 COMPARE_OP 0 (<)
44 JUMP_IF_FALSE 8 (to 55)
47 POP_TOP
48 SET_LINENO 4
51 BREAK_LOOP
52 JUMP_FORWARD 1 (to 56)
>> 55 POP_TOP
>> 56 JUMP_ABSOLUTE 9
>> 59 POP_TOP
60 POP_BLOCK
...
Using a do..while - loop, you'd have one jump less per iteration,
but because of the if..break you get one additional jump.
regards,
Mirko
PS: Sorry, if this has been discussed before.
More information about the Python-list
mailing list