[Tutor] lambda vs def

Roeland Rengelink r.b.rigilink@chello.nl
Wed, 04 Jul 2001 06:42:31 +0200


Hi Van,

An ounce of measurement beats a pound of argument.

VanL wrote:
> 
> Hello,
> 
> I have been experimenting with functional programming styles using
> python, and I was wondering about speed differences.  How different is
> 
> add = lambda x, y: x+y
> 
> from
> 
> def add(x, y): return x + y ?
> 

No difference, they're exactly the same thing (see below)

> Admittedly, this is a trivial example, but for functions called
> repeatedly, it would add up.
> 
> Also, how about eval()?  Is the cost for parsing prohibitive?
> 

The cost is prohibitive

Here's the output of the little Python program I've attached at the end.

function : 0.0673129558563
lambda : 0.0682300329208
eval : 3.12110495567
Lamdas are function objects
<function add1 at 0x810b68c> <function <lambda> at 0x810d1e4>
Bytecode function
          0 SET_LINENO               3

          3 SET_LINENO               4
          6 LOAD_FAST                0 (x)
          9 LOAD_FAST                1 (y)
         12 BINARY_ADD          
         13 RETURN_VALUE        
         14 LOAD_CONST               0 (None)
         17 RETURN_VALUE        
Bytecode lambda
          0 SET_LINENO               6
          3 LOAD_FAST                0 (x)
          6 LOAD_FAST                1 (y)
          9 BINARY_ADD          
         10 RETURN_VALUE        

--
import time

def add1(x, y):
    return x+y

add2 = lambda x, y: x+y

t = time.time()
for i in xrange(10000):
    r = add1(1, 2)
print 'function :', time.time()-t

t = time.time()
for i in xrange(10000):
    r = add2(1, 2)
print 'lambda :', time.time()-t

t = time.time()
for i in xrange(10000):
    r = eval('1+2')
print 'eval :', time.time()-t

print 'Lamdas are function objects'
print add1, add2
import dis
print 'Bytecode function'
dis.dis(add1)
print 'Bytecode lambda'
dis.dis(add2)
--

Hope this helps,

Roeland
-- 
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"