Created
March 18, 2025 09:20
-
-
Save anilkeshwani/4a23117d4eebbd2343bb6adca47cee0f to your computer and use it in GitHub Desktop.
Benchmark performance of defaultdict vs regular dict with explicit key check for tokenization use case
This file contains hidden or 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
| import random | |
| import string | |
| import timeit | |
| from collections import defaultdict | |
| # Generate a random list of words (simulating a corpus) | |
| random.seed(42) | |
| words = ["".join(random.choices(string.ascii_lowercase, k=5)) for _ in range(100000)] | |
| # Benchmark defaultdict(int) | |
| def using_defaultdict(): | |
| word_freqs = defaultdict(int) | |
| for word in words: | |
| word_freqs[word] += 1 | |
| # Benchmark regular dict with explicit check | |
| def using_regular_dict(): | |
| word_freqs = {} | |
| for word in words: | |
| if word in word_freqs: | |
| word_freqs[word] += 1 | |
| else: | |
| word_freqs[word] = 1 | |
| # Measure execution times | |
| defaultdict_time = timeit.timeit(using_defaultdict, number=1_000) | |
| regular_dict_time = timeit.timeit(using_regular_dict, number=1_000) | |
| print(f"{defaultdict_time = }") | |
| print(f"{regular_dict_time = }") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment