How smart is the Python interpreter?

Heiko Wundram modelnine at modelnine.org
Thu Jul 31 07:38:49 EDT 2008


Am Donnerstag, 31. Juli 2008 13:09:57 schrieb ssecorp:
> def str_sort(string):
> 	s = ""
> 	for a in sorted(string):
> 		s+=a
> 	return s
>
>
> if i instead do:
>
> def str_sort(string):
> 	s = ""
>         so = sorted(string)
> 	for a in so:
> 		s+=a
> 	return s
>
>
> will that be faster or the interpreter can figure out that it only has
> to do sorted(string) once? or that kind of cleverness is usually
> reserved for compilers and not interpreters?

In a statement of the form

for <name> in <iterable>:

the expression <iterable> will only be evaluated once (to retrieve an 
iterator), so basically, both ways of stating it are equivalent and make 
negligible difference in runtime (the second version will be slower, because 
you have additional code to assign/fetch a local).

Anyway, if you care about speed, probably:

def str_sort(string):
    return "".join(sorted(string))

will be the fastest way of stating this.

-- 
Heiko Wundram



More information about the Python-list mailing list