What makes Python a slow language ?
Python is a high-level language (than C or C++) thus Python itself manages details of a program like memory allocation, memory deallocation, pointers, etc. This makes writing codes in Python easier for programmers. Python code is first compiled into python Byte Code. The Byte Code interpreter conversion happens internally and most of it is hidden from the developer. Byte code is platform-independent and lower-level programming. Compilation of byte code is to ramp up the execution of source code. The source code compiled to byte code is then executed in Python’s virtual machine one by one, to carry out the operations. The virtual machine is an internal component of Python.
Internally Python code is interpreted during run time rather than being compiled to native code hence it is a bit slower.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Running of Python script v/s running of C/C++ code:
Python: First it is compiled into Byte Code. This Byte Code is then interpreted and executed by the PVM (Python Virtual Machine).
C/C++: The source code is compiled into Binary Code which can be directly executed by the CPU making them more efficient.
Major Reasons for Python being slow:
- Being Interpreted: Unlike native languages like C/C++, Python code gets interpreted at runtime instead of being compiled to native code at compile time. Python is an interpreted language, which means that the Python code we write must go through many, many stages of abstraction before it can become executable machine code.
- Just In Time (JIT) Compiler: Other interpreted languages like Java/.NET byte code run faster than Python’s byte code because their standard distribution includes a JIT compiler that compiles byte code into native code at run time. Python does not have a JIT compiler because the dynamic nature of Python makes it difficult to write one. It is impossible to say what type of parameters will be passed to a function, which makes optimization a bit harder.
- Global Interpreter Lock (GIL): It prevents multi-threading by mandating the interpreter to execute only a single thread within a single process (i.e. an instance of Python interpreter) at a time.