Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Last active January 19, 2019 19:56
Show Gist options
  • Save vlad-bezden/480faf33dbd2fdc2150bfbf1f4e278a0 to your computer and use it in GitHub Desktop.
Save vlad-bezden/480faf33dbd2fdc2150bfbf1f4e278a0 to your computer and use it in GitHub Desktop.
Performance results for different type of memory allocation
"""
List allocation with teh same value using different techniques
The winner is [value] * times by between 15-25 times
"""
from timeit import timeit
from itertools import repeat
SIZE = 10_000
INIT_VALUE = 0
def first():
"""Using itertools.repeat"""
return [x for x in repeat(INIT_VALUE, SIZE)]
def second():
"""Using range"""
return [INIT_VALUE for x in range(SIZE)]
def third():
return [INIT_VALUE] * SIZE
for x in [first, second, third]:
t = timeit(stmt=x, number=1_000)
print(f"{x.__name__}: {t}")
# first: 0.7676357779999999
# second: 1.0797578159999999
# third: 0.04752255700000019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment