Reputation: 329
I have these 3 functions:
def is_compatible(values):
supported_types = [(str, unicode), (int, long)]
for allowed_types in supported_types:
if isinstance(values[0], allowed_types):
return all(isinstance(item, allowed_types) for item in values)
return False
def is_compatible2(values):
supported_types = [(str, unicode), (int, long)]
for allowed_types in supported_types:
if all(isinstance(item, allowed_types) for item in values):
return True
return False
def is_compatible3(values):
supported_types = [(str, unicode), (int, long)]
return any(
all(isinstance(item, allowed_types) for item in values) for
allowed_types in supported_types
)
Can someone please explain to me, why when I run them with [1,2,3,4,5] as arg in timetit, results are 2.47, 3.07 and 3.94? So the first one is fastest and last one slowst. I simply cannot see any reason for these speed differences. Thanks.
Upvotes: 3
Views: 305
Reputation: 23827
Your answer appears to be here: Why is Python's 'all' function so slow?
Setting up the iterator in all
takes time.
In your first function you only do this once. In your second function you occasionally do this twice. So first beats second.
Your second beats third for the same reason again. There's more overhead to set up. A call to any
wrapped around the for allowed_types in ...
is more overhead than simply for allowed_types in ...
.
Upvotes: 2