2

(i5 ivybridge cpu windows 10) Map seems to come out slower every time, for what is a very long list, where it should do well

import time
l = [2049 for i in range(20000000)]
def f(e):
    return (e * 2) - 56

st = time.time()
l = list(map(f,l))
end = time.time()
print ("map: "+str(end-st))

l = [2049 for i in range(20000000)]

st = time.time()
l = [f(e) for e in l]
end = time.time()
print ("list comp: "+str(end-st))

prints:

map: 4.037442207336426
list comp: 3.9109268188476562
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ragardner
  • 1,836
  • 5
  • 22
  • 45
  • 4
    *"it should do well"* - what makes you say that? – jonrsharpe Jun 24 '17 at 20:07
  • @jonrsharpe I was under the impression that map "maps" the function to every element where as the list comprehension has to assess the function call for every iteration, so my thinking was that the longer the list the more advantage map() has – ragardner Jun 24 '17 at 20:08
  • 1
    It's not clear to me what you think the difference between *"[mapping] a function to every element"* and *"[assessing] the function call for every iteration"* is. You have to call `f` for every item in `l` either way; both are `O(n)`, it's only the fixed costs that vary. – jonrsharpe Jun 24 '17 at 20:10
  • @jonrsharpe I see – ragardner Jun 24 '17 at 20:10
  • 2
    The list comp also makes it easy to avoid the function call entirely in your case for a substantial increase in speed. – pvg Jun 24 '17 at 20:14
  • 1
    You could, however, since map returns a mapping object, run a for loop on it without having to build a list first(kind of like a generator), this might save you some(but not a lot) of time. Just for clarification, the map() function you run there takes about 0.0004 seconds to run - what takes the time is the list() operation. – doratheexplorer0911 Jun 24 '17 at 20:33
  • 1
    What I said is good especially for saving memory rather than speed. – doratheexplorer0911 Jun 24 '17 at 20:39

0 Answers0