In my code, I have a list l
, and I'm creating a dictionary of lists from it. (I'm grouping objects which have the same key
). Implementing it via both a try
statement and a if
condition, I've noticed in line_profiler that the former seems much more efficient :
Line # Hits Time Per Hit % Time Line Contents
==============================================================
293 44378450 59805020 1.3 16.9 for element in l:
# stuff that compute 'key' from 'element'
302 2234869 2235518 1.0 0.6 try:
303 2234869 82486133 36.9 23.3 d[key].append(element)
304 57358 72499 1.3 0.0 except KeyError:
305 57358 1758248 30.7 0.5 d[key] = [element]
vs:
Line # Hits Time Per Hit % Time Line Contents
==============================================================
293 44378450 60185880 1.4 14.0 for element in l:
# stuff that compute 'key' from 'element'
307 2234869 81683512 36.5 19.1 if key in d.keys():
308 2177511 76393595 35.1 17.8 d.get(key).append(element)
309 else:
310 57358 1717679 29.9 0.4 d[key] = [element]
I understand that with try
, you only go into except
when an exception is raised (so with few exceptions, it makes sense it cost less overall than testing the condition every time), but here, even the Time per hit
is slower for the exception (1.3+30.7 µs) than for the test condition (36.5 µs). I thought raising exception would be more costly than checking if a key is in the dictionary (in
just test the hash key, no ? It's not a line search). So why is that ?