Skip to content

Instantly share code, notes, and snippets.

@rnag
Created November 27, 2024 06:55
Show Gist options
  • Save rnag/dbe0342418ddb34bfa38b813729ac0f4 to your computer and use it in GitHub Desktop.
Save rnag/dbe0342418ddb34bfa38b813729ac0f4 to your computer and use it in GitHub Desktop.
Python: Compare `to string` conversion performance
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))
@rnag
Copy link
Author

rnag commented Nov 27, 2024

Results show that approach #2 or #3 are at least 2x faster than the first approach with as_str().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment