Skip to content

Instantly share code, notes, and snippets.

@nicktimko
Created March 14, 2019 23:50
Show Gist options
  • Save nicktimko/b047d178f7810e0dd7647089b90e95a5 to your computer and use it in GitHub Desktop.
Save nicktimko/b047d178f7810e0dd7647089b90e95a5 to your computer and use it in GitHub Desktop.
except vs get
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# `except KeyError` performance\n",
"\n",
"If it's common that the key isn't in the dictionary, then it makes a lot of sense to access it via `.get` with a default. If it's truly exceptional it doesn't exist and you'll want to do something special, then a `try` block is faster in the common case."
]
},
{
"cell_type": "code",
"execution_count": 148,
"metadata": {},
"outputs": [],
"source": [
"d = {'foo': 3}"
]
},
{
"cell_type": "code",
"execution_count": 149,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"62.3 ns ± 3.83 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n"
]
}
],
"source": [
"%%timeit\n",
"try:\n",
" result = d['foo'] * 2\n",
"except KeyError:\n",
" result = 0"
]
},
{
"cell_type": "code",
"execution_count": 150,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"89.8 ns ± 1.56 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n"
]
}
],
"source": [
"%%timeit\n",
"result = d.get('foo', 0) * 2"
]
},
{
"cell_type": "code",
"execution_count": 151,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"267 ns ± 25 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n"
]
}
],
"source": [
"%%timeit\n",
"try:\n",
" result = d['bar'] * 2\n",
"except KeyError:\n",
" result = 0"
]
},
{
"cell_type": "code",
"execution_count": 152,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"93.2 ns ± 5.52 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)\n"
]
}
],
"source": [
"%%timeit\n",
"result = d.get('bar', 0) * 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment