[Tutor] Re: What is "in-line code"?

Lee Harr missive at hotmail.com
Sat Aug 14 14:43:59 CEST 2004


>(<http://www.python.org/doc/essays/list2str.html>). There are many things
>I don't understand in it, but I'll ask about only one. What is "in-line
>code"? It appears in the Conclusion section, in "Try to use map(),
>filter() or reduce() to replace an explicit for loop, but only if you can
>use a built-in function: map with a built-in function beats for loop, but
>a for loop with in-line code beats map with a lambda function!"
>
>Also, "in-lining" is mentioned in "Avoid calling functions written in
>Python in your inner loop. This includes lambdas. In-lining the inner
>loop can save a lot of time."
>


"In-line" just means that the code is written out right there
in the body of the loop, instead of being in a separate
function which the loop calls.  For example ...

# Not In-line
>>>def add2(a, b):
...     return a + b
...
>>>pairs = [(1, 2), (3, 4), (5, 6)]
>>>for pair in pairs:
...     print add2(pair[0], pair[1])
...
3
7
11


# Same result with In-line code
>>>for pair in pairs:
...     print pair[0] + pair[1]
...
3
7
11


So, if what you are doing is very simple, you might choose not to
separate out add2() and just write the code in-line.

In python, functions calls are relatively "heavy" and if the pairs
list has many many elements you could get a noticeable speedup.

C compilers (and probably other languages too...) allow you to mark
some functions or methods as "in-line", which is nice since it allows
you to show the code as a separate entity (which helps maintenance)
but get the speed-up of actually copying the code in to the body
of the loop.

A different (but related?) optimization would be "unrolling" where the
code of the for loop is actually copied over and over instead of
wasting the time to jump back to the beginning of the code for the
next iteration.

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online 
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963



More information about the Tutor mailing list