Created
November 27, 2024 06:55
-
-
Save rnag/dbe0342418ddb34bfa38b813729ac0f4 to your computer and use it in GitHub Desktop.
Python: Compare `to string` conversion performance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from timeit import timeit | |
from dataclass_wizard.utils.type_conv import as_str | |
n = 100_000 | |
print('(int) as_str():'.ljust(25), timeit('x = 42; as_str(x)', globals=globals(), number=n)) | |
print('(int) str():'.ljust(25), timeit('x = 42; str(x)', globals=globals(), number=n)) | |
print('(int) empty_if_none():'.ljust(25), timeit("x = 42; '' if x is None else str(x)", globals=globals(), number=n)) | |
print() | |
print('(str) as_str():'.ljust(25), timeit('x = "hello world!"; as_str(x)', globals=globals(), number=n)) | |
print('(str) str():'.ljust(25), timeit('x = "hello world!"; str(x)', globals=globals(), number=n)) | |
print('(str) empty_if_none():'.ljust(25), timeit('x = "hello world!"; "" if x is None else str(x)', globals=globals(), number=n)) | |
print() | |
print('(bool) as_str():'.ljust(25), timeit('x = True; as_str(x)', globals=globals(), number=n)) | |
print('(bool) str():'.ljust(25), timeit('x = True; str(x)', globals=globals(), number=n)) | |
print('(bool) empty_if_none():'.ljust(25), timeit("x = True; '' if x is None else str(x)", globals=globals(), number=n)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results show that approach #2 or #3 are at least 2x faster than the first approach with
as_str()
.