Re: How smart is the Python interpreter?
- From: Heiko Wundram <modelnine@xxxxxxxxxxxxx>
- Date: Thu, 31 Jul 2008 13:38:49 +0200
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
.
- References:
- How smart is the Python interpreter?
- From: ssecorp
- How smart is the Python interpreter?
- Prev by Date: Re: working pylint anyone?
- Next by Date: Re: How smart is the Python interpreter?
- Previous by thread: Re: How smart is the Python interpreter?
- Next by thread: Re: How smart is the Python interpreter?
- Index(es):
Relevant Pages
|