gh-103193: Speedup and inline inspect._is_type
by AlexWaygood · Pull Request #103321 · python/cpython (original) (raw)
(Using @sobolevn's benchmark script from #103193 (comment).)
Benchmarks on main
:
type[Foo] : 74 ± 0 ns
Foo : 177 ± 1 ns
type[Bar] : 74 ± 0 ns
Bar : 177 ± 0 ns
WithParentClassX : 229 ± 0 ns
Baz : 216 ± 0 ns
WithParentX : 266 ± 1 ns
type[Missing] : 210 ± 0 ns
Missing : 219 ± 1 ns
Slotted : 214 ± 0 ns
Method : 178 ± 0 ns
StMethod : 178 ± 0 ns
ClsMethod : 178 ± 1 ns
Benchmarks with this PR:
type[Foo] : 74 ± 0 ns
Foo : 134 ± 0 ns
type[Bar] : 74 ± 0 ns
Bar : 133 ± 0 ns
WithParentClassX : 187 ± 0 ns
Baz : 171 ± 0 ns
WithParentX : 220 ± 0 ns
type[Missing] : 210 ± 1 ns
Missing : 174 ± 0 ns
Slotted : 169 ± 0 ns
Method : 133 ± 0 ns
StMethod : 133 ± 0 ns
ClsMethod : 133 ± 0 ns
This speeds up this isinstance()
call 1.25x relative to main
:
from typing import *
@runtime_checkable class Foo(Protocol): a: int b: int c: int d: int e: int f: int g: int h: int i: int j: int
class Bar: def init(self): for attrname in 'abcdefghij': setattr(self, attrname, 42)
isinstance(Bar(), Foo)