Initializing deque with iterator is significantly slower than appending later to an empty deque
It seems d = deque([x])
is significantly slower than d = deque(); d.append(x)
, where x: int
.
Both run in the almost same speed in CPython.
Does this difference come from the implementation of deque in PyPy? Or due to a heavy cost of generating a list?
import time
from collections import deque
def main():
n = 10 ** 6
x = 1
start = time.perf_counter()
for _ in range(n):
_ = deque([x])
print(f"Using init: {time.perf_counter() - start}")
start = time.perf_counter()
for _ in range(n):
d = deque()
d.append(x)
print(f"Using append: {time.perf_counter() - start}")
if __name__ == "__main__":
main()
❯ pypy3 main.py
Using init: 0.1269904590008082
Using append: 0.0021725459992012475
❯ pypy3 --version
Python 3.6.9 (2ad108f17bdb, Apr 07 2020, 02:59:26)
[PyPy 7.3.1 with GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.32.29)]
> sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.6
BuildVersion: 18G6020
> xcodebuild -version
Xcode 11.3.1
Build version 11C504
> python3 --version
Python 3.8.5