What Is Easier For Machine - Dictionary Comprehension Or Deepcopy Of Existing Dictionary?
Initializing a function I need two same dictionaries, one of them I can only create with dict. comprehension. But when it came to second one I got curious if it is easier (less time and/or fewer operations) for machine to make it as a deepcopy of the first one or rather repeat the same comprehension.
I usually set both as comprehensions 'cause my dictionaries are generally small, but when there are not empty values and/or more keys it may matter.
# both as comprehensions (implying I already have keys)
dict1 = {key: [] for key in keys}
dict2 = {key: [] for key in keys}
# second one as a deepcopy of the first
dict1 = {key: [] for key in keys}
dict2 = copy.deepcopy(dict1)
Well, I don't expect big difference for my case but I am just curious how it works in general.
Answer
deepcopy
does a lot more work/checking than your first example, a simple timing exercise confirms this:
In [1]: import copy
...:
...: dict1 = {key: [] for key in 'abcdefgh'}
...:
...: %timeit dict2 = {key: [] for key in 'abcdefgh'}
...:
...: %timeit dict2 = copy.deepcopy(dict1)
...:
816 ns ± 5.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
21 µs ± 28.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you know in advance your data structure (i.e. the level of nesting and types etc.), then you can make decent performance gains by avoiding deepcopy
. However, deepcopy
is more flexible of course.
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module