TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Try/Except vs. If in Dictionary Key Access Python Performance

2 pointsby ilhicasabout 7 years ago

2 comments

dozzieabout 7 years ago
This is exactly why you need to take some algorithms and data structures lecture. Who in their right mind would think that checking if a key is present in a hash map takes O(n) time by generating a list of all keys and linear search when extracting the value from under that key takes O(1)?
评论 #16948379 未加载
carapaceabout 7 years ago
Use try..except.. when you expect it to mostly succeed.<p><pre><code> $ python -m timeit -s &quot;a={k:k for k in range(10000)}&quot; &#x27;try: b=a[10001] except: pass&#x27; 1000000 loops, best of 3: 0.276 usec per loop $ python -m timeit -s &quot;a={k:k for k in range(10000)}&quot; &#x27;try: b=a[1] except: pass&#x27; 10000000 loops, best of 3: 0.0255 usec per loop </code></pre> &quot;try&quot; is <i>fast</i>, &quot;except&quot; is slow
评论 #16948355 未加载
评论 #16948247 未加载