This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Peephole optimization: returning a temp
Type: Stage:
Components: None Versions: Python 2.7
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: rhettinger Nosy List: georg.brandl, novalis_dt, rhettinger
Priority: low Keywords: patch

Created on 2008-10-16 19:54 by novalis_dt, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
peephole-return-temp.diff novalis_dt, 2008-10-16 19:54
Messages (5)
msg74853 - (view) Author: David Turner (novalis_dt) Date: 2008-10-16 19:54
This patch adds an optimization to the peephole optimizer for the common
case of:

def func(...):
   ...
   retval = ...
   return retval

Before the patch, the compiler would generate
STORE_FAST 3
LOAD_FAST 3
RETURN_VALUE

The store and load are pointless, as the local 3 (or whatever) is never
used again.  This patch makes the peephole optimizer optimize them out.
msg74866 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2008-10-16 21:32
Sorry, am not excited by this one.  It is not a common idiom in most
code that I've ever seen and it never occurs in an inner-loop.  Besides
the load_fast/store_fast combination are so *very* fast that any real
code would not see a worthwhile speedup.

When the AST optimizer gets built-out, I expect that we'll get many of
these sort of optimizations for free.  In the meantime, this one just
isn't worth adding complexity to the peepholer.
msg74867 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2008-10-16 21:34
I wonder why people don't just write "return ..." in the first place...
msg74876 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2008-10-16 22:48
Agreed.
msg74881 - (view) Author: David Turner (novalis_dt) Date: 2008-10-16 23:33
The idiom appears at least 370 times in the standard library.  And,
while on its own it can't appear in a loop, a function that uses it
might get called in a loop.   

You mention some sort of AST optimizer.  I haven't really followed
Python development enough to know anything about this.  Is it worth
bothering to do other work on the peepholer which might handle some more
common cases?  If not, is there a branch or something where I can look
at the AST optimizer?
History
Date User Action Args
2022-04-11 14:56:40adminsetgithub: 48384
2008-10-16 23:33:30novalis_dtsetmessages: + msg74881
2008-10-16 22:48:21rhettingersetstatus: open -> closed
resolution: rejected
messages: + msg74876
2008-10-16 21:34:59georg.brandlsetnosy: + georg.brandl
messages: + msg74867
2008-10-16 21:32:44rhettingersetpriority: low
assignee: rhettinger
messages: + msg74866
nosy: + rhettinger
2008-10-16 19:54:09novalis_dtcreate