I'm an idiot

Christian Tismer tismer at tismer.com
Sat Jun 29 17:24:25 CEST 2002


Fredrik Lundh wrote:
> Joseph A Knapka wrote:

...

>>But I'm sure there are Very Good Reasons not to do this,
>>and that some wise person will presently educate me :-)
> 
> 
> To many people, this is a religous topic.  Google can probably
> tell you all about the different religions.
> 
> The most common view is that as the name implies, exceptions
> should be used to deal with exceptional, unexpected conditions.
> That you'll reach the end of a file if you keep reading data from
> it should hardly come as a surprise...

Well, there *might* be one other reason, while maybe
not too remarkable, but the following examples show
that using exceptions just for the sake of speed
may be a consideration.

Test 1 iterates over realines() output (well, kidding,
I just used a cont string) and asks if the string is
empty.
Test 2 does it different, by wrapping the whole loop
into a try...except and does a test by indexing the
string, which will raise an IndexError on failure.
Test 3 is just an empty loop for comparison.

 >>> def test1(n):
... 	s='abc'
... 	for i in xrange(n):
... 		if not s:
... 			break
... 		
 >>> def test2(n):
... 	s="abc"
... 	try:
... 		for i in xrange(n):
... 			s[0]
... 	except IndexError:
... 		pass
... 	
 >>> def test3(n):
... 	for i in xrange(n):
... 		pass
... 	
 >>> timing(test1, 1000000)
(0.99099999999999999, None)
 >>> timing(test2, 1000000)
(0.90100000000000002, None)
 >>> timing(test3, 1000000)
(0.5, None)
 >>>

Comparing the results suggests, that an exception
based solution is 20 percent faster, or even better.
Since the string must be touched anyway if we want
to do something with it, it can be managed to write
the string processing in a way, that the above
exception raising indexing is performed as a side
effect of the processing, if written carefully.

I have to admit that this all doesn't increase
readability, it's just a trick that came to mind.

For the general case, I really recommend to follow
your advice!

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at tismer.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34  home +49 30 802 86 56  pager +49 173 24 18 776
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/







More information about the Python-list mailing list