4 ms·
> It's instructive to look at javascript and python. Javascript engines are much faster than python engines because Javascript doesn't do threads. I don't thin
by noelwelsh 2y ago
> It's instructive to look at javascript and python. Javascript engines are much faster than python engines because Javascript doesn't do threads.
I don't think this is the primary difference. While JS's semantics are bad for performance, Python's are insance. Two examples:
- In Python you can change the meaning of operators, so that 1 + 2 could mean something very different from integer addition. This can happen at any point within a program, so you must always guard against the possibility that basic arithmetic---some of the fastest operations on a CPU---has changed meaning. This slows things down considerably. JS is fairly dynamic but AFAIK it's impossible to change this.
- Python allows inspecting the stack (https://docs.python.org/3/library/inspect.html#the-interpreter-stack https://docs.python.org/3/library/inspect.html#the-interpret...) so at any point in your program you have to be prepared to reflect the stack as Python objects. Bye-bye performance.
- gizmo 2y agoYou can't actually override operator_plus in Python for numbers. Numbers in Python are magic for performance reasons. You can look at the Python bytecode to easily see this: def add_five(a): return a + 5 dis.dis(add_five) And this returns something like: LOAD FAST a LOAD CONST 5 BINARY ADD RETURN ACC
- gergo_barany 2y agoYou're right that you can't override __add__ for numbers, but the bytecode doesn't say this. The bytecode isn't specialized to numbers. It will call the __add__ operation on whatever object you give it. The interpreter will probably have a fast path in its implementation of the BINARY_OP instruction that checks for numbers. But that doesn't mean that the BINARY_OP instruction can only handle numbers. Example: >>> class foo(object): ... def __add__(x, y): ... print(f'"adding" {x} and {y} by returning {y}+1', x, y, y) ... return y + 1 ... >>> f = foo() >>> f + 3 "adding" <__main__.foo object at 0x725f470c4e90> and 3 by returning 3+1 <__main__.foo object at 0x725f470c4e90> 3 3 4 >>> add_five(f) "adding" <__main__.foo object at 0x725f470c4e90> and 5 by returning 5+1 <__main__.foo object at 0x725f470c4e90> 5 5 6 (Not sure why there's extra garbage printed, my Python is a bit rusty.)