TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

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

2 点作者 ilhicas大约 7 年前

2 条评论

dozzie大约 7 年前
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 未加载
carapace大约 7 年前
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 未加载