Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
In [1]: import timeit
In [4]: class A(object):
...: pass
...:
In [5]: item = object()
In [6]: item_a = A()
In [7]: def descendent_isinstance():
...: return isinstance(item_a, object)
...:
In [8]: def direct_isinstance():
...: return isinstance(item_a, A)
...:
In [9]: def direct_isinstance_builtin():
...: return isinstance(item, object)
...:
In [10]: def not_isinstance():
...: return isinstance(item, A)
...:
In [11]: descendent_isinstance()
Out[11]: True
In [12]: direct_isinstance()
Out[12]: True
In [14]: direct_isinstance_builtin()
Out[14]: True
In [15]: not_isinstance()
Out[15]: False
In [17]: tests = {
...: "descendent_isinstance": descendent_isinstance,
...: "direct_isinstance": direct_isinstance,
...: "direct_isinstance_builtin": direct_isinstance_builtin,
...: "not_isinstance": not_isinstance,
...: "item": item,
...: "item_a": item_a,
...: "A": A,
...: }
In [18]: timeit.repeat(stmt="descendent_isinstance()", globals=tests)
Out[18]:
[0.18606656999997995,
0.17976311300003545,
0.17793933600000855,
0.17901940199999444,
0.1791184380000459]
In [19]: timeit.repeat(stmt="direct_isinstance()", globals=tests)
Out[19]:
[0.16835473799994816,
0.16796777699994436,
0.16732346500009498,
0.1671851889999516,
0.1646581120000974]
In [20]: timeit.repeat(stmt="direct_isinstance_builtin()", globals=tests)
Out[20]:
[0.17491985099991325,
0.17345420999993166,
0.17239584300000388,
0.1734395940000013,
0.17397786800006543]
In [21]: timeit.repeat(stmt="not_isinstance()", globals=tests)
Out[21]:
[0.19989036399999804,
0.1967721519999941,
0.1962455799999816,
0.19687672300005943,
0.19701133199998822]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.