kbandla / dpkt

fast, simple packet creation / parsing, with definitions for the basic TCP/IP protocols
Other
1.09k stars 270 forks source link

hasattribute usage vs getattribute or try/ except #454

Closed KaliszAd closed 5 years ago

KaliszAd commented 5 years ago

In https://github.com/kbandla/dpkt/blob/8c15c6ca21461996eefe80274f9ba7e7548a796f/dpkt/__init__.py#L83-L85 it would probably be better to implement with getattribute or try/ except. If the case hasattr(mod, '_mod_init') is mostly true and only sometimes false, this could even yield better performance. See discussion here.

kbandla commented 5 years ago

Interesting - looking at this bench from that discussion :


       |positive|negative
hasattr|  0.446 |  1.87 
try    |  0.247 |  3.13

so it is ~2x as fast if positive, and ~1.6x slower if negative.

There are only 4 modules, out of some 70, which actually have _mod_init - so the case is mostly negative:

dpkt/aoe.py:def _mod_init():
dpkt/ethernet.py:def _mod_init():
dpkt/ip.py:def _mod_init():
dpkt/ppp.py:def _mod_init():

But its nice trick to know, thanks!