Skip to content

Instantly share code, notes, and snippets.

@SaswatPadhi
Last active July 2, 2019 06:03
Show Gist options
  • Save SaswatPadhi/eef95e7deb01f54725e013f6cd09aa19 to your computer and use it in GitHub Desktop.
Save SaswatPadhi/eef95e7deb01f54725e013f6cd09aa19 to your computer and use it in GitHub Desktop.
# https://stackoverflow.com/a/56844986/554436
def test(s):
d = {"foo": "foo", "bar": "bar"}
return d.get(s)
if __name__ == '__main__':
from dis import dis
from timeit import timeit
code_1 = '"foo" in {test("foo"), test("tar")}'
code_2 = '"foo" == test("foo") or "foo" == test("tar")'
print('--------')
print(code_1)
print(dis(code_1))
print(code_2)
print(dis(code_2))
print('--------')
print(code_1)
print(timeit(code_1, setup="from __main__ import test"))
print(code_2)
print(timeit(code_2, setup="from __main__ import test"))
# OUTPUT:
# --------
# "foo" in {test("foo"), test("tar")}
# 1 0 LOAD_CONST 0 ('foo')
# 2 LOAD_NAME 0 (test)
# 4 LOAD_CONST 0 ('foo')
# 6 CALL_FUNCTION 1
# 8 LOAD_NAME 0 (test)
# 10 LOAD_CONST 1 ('tar')
# 12 CALL_FUNCTION 1
# 14 BUILD_SET 2
# 16 COMPARE_OP 6 (in)
# 18 RETURN_VALUE
# None
# "foo" == test("foo") or "foo" == test("tar")
# 1 0 LOAD_CONST 0 ('foo')
# 2 LOAD_NAME 0 (test)
# 4 LOAD_CONST 0 ('foo')
# 6 CALL_FUNCTION 1
# 8 COMPARE_OP 2 (==)
# 10 JUMP_IF_TRUE_OR_POP 22
# 12 LOAD_CONST 0 ('foo')
# 14 LOAD_NAME 0 (test)
# 16 LOAD_CONST 1 ('tar')
# 18 CALL_FUNCTION 1
# 20 COMPARE_OP 2 (==)
# >> 22 RETURN_VALUE
# None
# --------
# "foo" in {test("foo"), test("tar")}
# 0.5012693479948211
# "foo" == test("foo") or "foo" == test("tar")
# 0.25610274499922525
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment