Python is a high-level language (higher than C or C++), therefore it handles program minutiae like memory allocation, memory deallocation, pointers, and so on. This makes it easy for programmers to write Python programs. Python code is converted into python Byte Code initially. Internally, the Byte Code interpreter conversion occurs, and the majority of it is hidden from the developer. Byte code is a lower-level programming language that is platform-independent. The purpose of byte code compilation is to speed up the execution of source code. To carry out the operations, the source code is compiled to byte code and then run one by one in Python’s virtual machine. Python’s virtual machine is a built-in feature.
Internally Python code is interpreted during run time rather than being compiled to native code hence it is a bit slower.
Python script execution vs. C/C++ code execution:
Python: It is first converted to Byte Code. The PVM (Python Virtual Machine) then interprets and executes this Byte Code.
C/C++: The code is compiled to Binary Code, which may be directly performed by the CPU, resulting in increased efficiency.
The following are the main causes of Python’s slowness:
- Being Translated: Python code, unlike native languages like C/C++, is interpreted at runtime rather than compiled to native code at build time. Python is an interpreted language, which means that the Python code we write must go through several abstraction steps before becoming machine code that can be executed.
- Compiler for Just In Time (JIT): Other interpreted languages, such as Java/.NET byte code, run quicker than Python byte code because they come with a JIT compiler that translates byte code into native code at runtime. Python does not have a JIT compiler since it is difficult to create one due to the dynamic nature of the language. It’s impossible to predict what kind of parameters will be supplied to a function, making optimization more difficult.
- GIL (Global Interpreter Lock): It prevents multi-threading by requiring the interpreter to run only one thread at a time within a single process (i.e. a Python interpreter instance).
Pretty interesting stuff!
If you want to learn more about Python, check out our course!
And if all this reading has got you considering a lower-level language that is faster, try out our Java course!