Cheap exception handling in Python?

后端 未结 8 1055
广开言路
广开言路 2020-12-05 17:34

I read in an earlier answer that exception handling is cheap in Python so we shouldn\'t do pre-conditional checking.

I have not heard of this before, but I\'m relati

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 18:28

    With Python, it is easy to check different possibilities for speed - get to know the timeit module :

    ... example session (using the command line) that compare the cost of using hasattr() vs. try/except to test for missing and present object attributes.

    % timeit.py 'try:' '  str.__nonzero__' 'except AttributeError:' '  pass'
    100000 loops, best of 3: 15.7 usec per loop
    % timeit.py 'if hasattr(str, "__nonzero__"): pass'
    100000 loops, best of 3: 4.26 usec per loop
    % timeit.py 'try:' '  int.__nonzero__' 'except AttributeError:' '  pass'
    1000000 loops, best of 3: 1.43 usec per loop
    % timeit.py 'if hasattr(int, "__nonzero__"): pass'
    100000 loops, best of 3: 2.23 usec per loop
    

    These timing results show in the hasattr() case, raising an exception is slow, but performing a test is slower than not raising the exception. So, in terms of running time, using an exception for handling exceptional cases makes sense.

    EDIT: The command line option -n will default to a large enough count so that the run time is meaningful. A quote from the manual:

    If -n is not given, a suitable number of loops is calculated by trying successive powers of 10 until the total time is at least 0.2 seconds.

提交回复
热议问题