我正在优化我的代码以提高性能,当我用来cProfile
检查我的代码时,大量的运行时间是由于类型注释造成的!删除类型注释确实可以提高性能。cProfiler
您可以在下面看到带注释和不带注释的输出。
带注释的明显使用了__call__
、__new__
、inner
、__getitem__
、__hash__
等方法typing.py
,而且比不带注释的慢了一倍!
我的测试代码很简单:
from reil.datatypes import reildata
x = reildata.Categorical(name='cat', categories=('A', 'B', 'C', 'D', 'E'))
for _ in range(10000):
[x(v) for v in ('A', 'B', 'C', 'D', 'E')]
Run Code Online (Sandbox Code Playgroud)
这是主代码的相关部分(datatypes.reildata.py
):
from __future__ import annotations
import dataclasses
import itertools
from dataclasses import field
from typing import Any, Callable, Dict, Generic, Iterable, Iterator, List, Optional, Sequence, Tuple, TypeVar, Union, cast
from typing_extensions import …
Run Code Online (Sandbox Code Playgroud)