#28769: Utilize 'x or y' in place of 'x if x else y'
-------------------------------------+-------------------------------------
Reporter: Дилян Палаузов | Owner: nobody
Type: | Status: closed
Cleanup/optimization |
Component: Core (Other) | Version: 1.11
Severity: Normal | Resolution: fixed
Keywords: | Triage Stage: Ready for
| checkin
Has patch: 1 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by Adam (Chainz) Johnson):
Nice, this is also a little faster (at least, fewer opcodes, the time
difference is minimal):
{{{
> default ~ 👾 ❯ ipython
Python 3.6.0 (default, Dec 24 2016, 08:01:42)
Type "copyright", "credits" or "license" for more information.
IPython 5.3.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]:
Do you really want to exit ([y]/n)? n
In [1]: def foo(a=1, b=2):
...: return a if a else b
...:
In [2]: def bar(a=1, b=2):
...: return a or b
...:
In [3]: import dis
In [4]: dis.dis(foo)
2 0 LOAD_FAST 0 (a)
2 POP_JUMP_IF_FALSE 8
4 LOAD_FAST 0 (a)
6 RETURN_VALUE
>> 8 LOAD_FAST 1 (b)
10 RETURN_VALUE
In [5]: dis.dis(bar)
2 0 LOAD_FAST 0 (a)
2 JUMP_IF_TRUE_OR_POP 6
4 LOAD_FAST 1 (b)
>> 6 RETURN_VALUE
In [6]: %timeit foo()
The slowest run took 8.95 times longer than the fastest. This could mean
that an intermediate result is being cached.
10000000 loops, best of 3: 115 ns per loop
In [7]: %timeit bar()
10000000 loops, best of 3: 108 ns per loop
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/28769#comment:5>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/072.0073a139603c48778d5080067ec16a69%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.