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

Kent Johnson kent_johnson at skillsoft.com
Sat Aug 14 13:38:04 CEST 2004


By 'in-line code' he means code written in C, i.e. using builtin 
capabilities of Python rather than user-written code.

For example this function is an example of reduce with lambda (not in-line):


     def f2(list):
         return reduce(lambda string, item: string + chr(item), list, "")


When this runs, the interpreter has to call back into user code for the 
lambda. reduce() itself is written in C but the callback function is not. 
This is a significant performance hit. On the other hand, in this function


     def f6(list):
         return string.joinfields(map(chr, list), "")


the callback is a builtin (chr()) so the map operation is entirely in C 
(in-line) and it is very fast.

Note the article you cite is out-of-date in a few minor ways. The usual way 
to join a list is now with the join method of the string, so f6 might be 
written as


     def f6(list):
         return "".join(map(chr, list))


The string module is implemented in Python and string.joinfields(word, sep) 
delegates to sep.join(words), so this version would probably be faster in 
modern Python.

Second, the timeit module replaces Guido's homebrew timing function.

You might be also be interested in this recent post: 
http://mail.python.org/pipermail/tutor/2004-July/030787.html

I'm kind of an optimization junkie so feel free to ask more questions :-)

Kent

At 02:29 AM 8/14/2004 -0700, Dick Moores wrote:
>I've been trying to read Guido van Rossum's essay, "Python Patterns - An 
>Optimization Anecdote" (<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."
>
>Thanks, tutors.
>
>Dick Moores
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list