Is Python faster and lighter than C++?

Python's advantages are code readibility and development speed, but time and memory usage are not as good as those C++.

According to the stats, Python is up to about 400 times slower than C++ and with the exception of a single case. Python is more of a memory hog. However, when it comes to source size though, Python wins flat out.

Why Python is slow?

My experiences with Python show the same definite trend that Python is on the order of between 10 and 100 times slower than C++ when doing any serious number crunching. There are many reasons for this, the major ones are:

  1. Python is a scripting language, it is interpreted, while C++ is compiled;
  2. Python has no primitives, everything including the built-in types (int, float, etc.) are objects;
  3. A Python list can hold objects of different type, so each entry has to store additional data about its type;

These all severely hinder both runtime and memory consumption.

Note: Python can be compiled, but Python is considered a scripting language because of a historical reason and the general use of "type it and go".

When to use Python?

This is no reason to ignore Python though. A lot of software doesn't require much time or memory even with the 100 time slowness factor.

Development cost is where Python wins with the simple and concise style. This improvement on development cost often outweighs the cost of additional cpu and memory resources. When it doesn't, however, then C++ wins.

References & Resources

  • N/A