Comparative Analysis of C++ and Python in Terms of Memory and Time
Comparative Analysis of C++ and Python in Terms of Memory and Time
Comparative Analysis of C++ and Python in Terms of Memory and Time
v1
Abstract— In this era of technology, programming has become terms of execution time is done in section [V]. Section [VI]
more significant than ever before. Python and C++ are both shows the memory and time analysis of algorithms in both
widely used programming languages. Python, the most popular languages. Section [VII] discusses the benefits and issues of
programming language in today’s world, is a high-level both C++ and Python and gives recommendations for
object-oriented language whereas C++, the language behind most
beginners. Section [VIII] concludes the paper and section [IX]
operating systems, is a low-level object-oriented language. In this
paper, we present a comparative study of Python and C++. This comprises references.
paper discusses the introduction to these languages, their
memory management techniques, and the reasons behind their II. BACKGROUND
program execution speed. Furthermore, we analyzed the
execution time and memory used by multiple algorithms in both With the emerging time, many programming languages are
the languages with best, average, and worst cases. They are also being introduced in the field of computer science. Each
compared with respect to the benefits and issues related to them. language has its own importance, and they also have their
Results indicate that C++ is faster than Python in execution speed drawbacks. But which language should be used by beginners
but Python serves as a better language for beginners due to its
simplicity. Moreover, for the best results, the language should be and which language should be used for fast working and
selected according to the type of project. precise results? This query is faced by almost all developers.
Zakaria Alomari, Oualid El Halimi, Kaushik Sivaprasad, and
Keywords— benefits, c++, comparative study, execution speed, Chitrang Pandit compared C++, PHP, C#, Java, Python, and
memory management, python VB in this paper [1] on the basis of paradigms, application
areas, execution strategy, typing strategy, memory
I. INTRODUCTION management, and available IDEs. For analysis of all features
of languages, the same algorithm has been executed in all
showed the efficiency of the Dynamic Javascript array in With the passage of time, C++ was updated and new
comparison to standard C++ arrays. This paper concluded that features were introduced in it such as classes, inheritance,
C++ is relatively faster than Javascript or any scripting static and constant member functions, templates, libraries, and
language such as Python because C++ is a compiled language namespaces. C++ is standardized by the International
and doesn't require any time to be translated into machine Organization Standardization (ISO) and published in 2011.
code. On the other hand, scripting languages require an A number of programming languages developed on the basis
interpreter that first translates the code then executes it. of C++. C# uses C++ syntax and its major features like
classes. In fact, the most popular programming language, Java
Another study about the comparison between programming is obtained from C++ but excludes its features like a pointer,
languages namely, Python and C++ was conducted. The operator overloading, and multiple inheritance just to keep the
authors compared the languages based on efficiency. For this language simple [1].
purpose, they utilized the sorting algorithms (Quicksort, C++ supports both object-oriented and procedure-oriented
Merge Sort, Bubble Sort, and Insertion Sort). They calculated programming but actually, it is an Object-Oriented
the execution time of each sorting algorithm in both languages Programming language that is largely used in real-world
in two ways. First, without showing data in array, and second, applications. It is considered to be an efficient language in
with showing data in array. They also used two ways to terms of memory and speed as compared to other
compile the code namely, Command Prompt and Cygwin. The programming languages like Java, python, etc [6].
results showed that Python took shorter to complete in Cygwin
and longer in CMD whereas the results of C++ were converse. B. Overview of Python
Furthermore, both the languages run faster when not showing
data in array [3]. In the late 1980s or early 1990s, at the National Research
Institute for Mathematics and Computer Science, Netherlands
In another study [4] conducted by Muhammad Ateeq, Hina Guido van Rossum developed a programming language called
Habib, Adnan Umer, Muzammil Ul Rehman, discussed the Python. It is derived from many other languages, including
choices of programming languages for a beginner of Modula-3, C, C++, Algol-68, and other scripting languages.
programming and from the paper, it is concluded that python Python is currently one of the most popular dynamic
is easy to learn and user-friendly language which is much programming languages, along with others such as Perl, Ruby,
alike English, majority of beginners express satisfaction and etc. It is a popular high-level programming language with high
comforts while learning python due to its syntax. Other code readability. Unlike other languages such as C++, C, Java,
languages like C++, Java, and many more have their etc, it uses indentation instead of brackets and semicolons [1].
importance at their places but students or beginners should It started gaining popularity in 2003 and now in 2020
always go with Python and don’t learn C++ until it is required according to PYPL PopularitY of Programming Language
because C++ has more syntax rules and other programming Index, Python tops the chart. There are two broad versions of
conventions but in some cases, you can surely go for C++. Python namely, 2.x and 3.x. It supports programming
C++ is the best option for game development and systems. paradigms such as functional, procedural, reflective,
Python is the most powerful programming language compared imperative, and object-oriented approaches [8].
to any other programming language.
This paper presents a comparative study of Python and C++ IV. MEMORY MANAGEMENT
under the characteristics of memory allocation, speed,
The memory system is a prime determinant of performance
advantages, and disadvantages. The objective of writing this
[9]. The process of allocating, deallocating, and managing
paper is to analyze and compare Python with C++ and find out
memory effectively is called memory management. It
about their implementation due to a famous statement about
basically refers to the allocation of memory when required by
Python that it is very slow. Hence, the research questions
the program and then frees it when it’s no longer required.
were: Is python slow? If yes, why? Which is better for
Since, how much memory is required for running an
beginners?
application cannot be estimated therefore, additional code is
required to manage changing memory requirements. There are
III. OVERVIEW OF C++ AND PYTHON two related tasks of memory management:
A. Overview of C++ 1) Allocation: Allocation of memory on the request of
the program for the block of memory. This block of memory
C++ is a general-purpose compiled language. It was is received from the operating system. The part of the memory
developed in 1979 by Danish Computer scientist “Bjarne manager that performs this, is known as the allocator.
Stroustrup” It is an extension of the C language and 2) Recycling: Once the memory blocks have been
considered a superset of the C language. Its first edition was allocated, but no longer required, then they are recycled either
released in 1985 [5]. by manual memory management in which the programmer
decides this or by automatic memory management in which
the memory manager does this work [10]
Preprints (www.preprints.org) | NOT PEER-REVIEWED | Posted: 21 December 2020 doi:10.20944/preprints202012.0516.v1
As a result of malloc () failure, a null pointer is returned generation if it still has a reference. The same is repeated for
whereas the new operator throws an exception. So better to generations 2 and 3, but with the lower thresholds of 10 [15].
use a new operator for memory allocation in C++ [12]. This process further extends to the lower level as depicted
by Figure 1 where the interpreter (CPython, PyPy, etc)
B. Memory Management in Python interacts with the OS's memory manager to deal with the
memory.
Python is a high-level programming language implemented
in C language. It handles everything in the form of objects
e.g., list, dictionary, tuple, integers are all stored as an object.
All these data structures and Python objects are stored in a
private heap managed by the Python memory manager.
Four concepts related to the Python memory manager are:
1. Heap: It is the collection of all Python managed
memory.
2. Arenas: These are the largest chunks of memory
which has a fixed size of 256 KB each. Python
requests them from the system and they are the
objects that make up the heap.
3. Pools: These are the chunks of memory that make up
the arenas of 4 KB each. They are simply arrays due
to their fixed sizes.
4. Blocks: Python objects are stored in blocks. They
have a specific format based on their data types. For
instance, an integer takes up more space than a
character, for efficiency a different block size is used.
Writing code in C++ is somehow difficult as compared to 1. Reasons behind Slow Execution
Python but when it comes to performance, C++ gives
excellent results. Research proves that languages like Python, The reasons behind its slow execution speed are mentioned
PHP, Java, and C# cannot compete with C++ in terms of speed below:
and memory efficiency. Following are the reasons behind the
fast performance of C++. ● Dynamically Typed Language
A dynamically typed language means it doesn’t require the
1. Statically Typed Language: variable type to be mentioned. A single python variable can
store any data type be it list, dictionary, int, string, etc.
C++ uses a static typing method. Data types are fixed like Therefore, when the program is executing, the interpreter
integer, float, char, and string. Every variable is stored with its checks the variable's data type every time it performs any
data type. The compiler already knows the data type of the operation to ensure the operation can be performed on that
variable and chooses an appropriate process for that particular variable. This process requires more time making the
variable. This means that in C++, there is no need to check the execution slow [19].
validation of type conversion at run time. This enhances the
performance of C++ as it favors the execution process at run ● Global Interpreter Lock (GIL)
time. GIL is required in Python to prevent multiple threads to alter
memory, at the same time corrupting memory. Since the
2. C++ is a Compiled Language: Python memory manager is not thread-safe therefore, it
requires GIL which prevents memory corruption by only
Unlike interpreted languages like Python in which the source executing a single thread at a time which slows down the
code is first translated into the byte code by an interpreter and speed of program execution [20].
then converted into machine code at run time, C++ allows
direct conversion of source code into machine code as it is a ● High-level language
compiler-based language. This results in a high improvement Python is a high-level language which means it is closer to
in execution speed [1]. human language. It requires less effort to write code because
of several reasons such as automatic memory management,
3. Dynamic Memory Allocation: garbage collection, etc [21].
Since C++ facilitates the programmer through the dynamic ● Garbage Collection
allocation of memory and enables him to declare and control Since Python uses a garbage collector, it takes time for it to
the lifetime of objects, it doesn't use a garbage collector.. This identify what memory to free. This process increases the
removes the additional time requirement in which a Java runtime of the program.
Virtual Machine or Python interpreter must stop for a while
and trace the object's lifetime. Hence, your C++ code runs 2. Different Kinds of Python Implementation:
faster [17].
After all these reasons, the reason that your python code is
4. Use of Templates: executing slowly can be the interpreter you are using. Rick
van Hattem presented a comparison of three different
C++ provides a strong feature of templates. These templates interpreters in his book “Mastering Python” to show the
improve run time performance because they mostly do difference between the speed of execution by different Python
computation at compile time. This may increase the interpreters on a test code. He used 3 interpreters namely,
compilation time but still run time performance is much better Python 3, Python 2, PyPy. Python 2 and 3 are CPython and
than Python. For large numerical problems, expression concluded that for this test code, the used version of PyPy
interpreter is more than 4 times faster than the CPython
templates are used. They solve vectors and matrices
version used [22].
efficiently. They perform most of the matrix operations such
as transposition without creating an intermediate matrix which Similarly, we carried out a test. We used multiple different
saves memory and leads to better performance. sets of codes and got the execution time of code for CPython
and PyPy (Python 3.7) and we concluded that PyPy is usually
B. Time Analysis in Python faster than CPython due to JIT (Just In Time) Compiler which
directly converts source code to machine code whereas
Python is a dynamically typed language. It has a simple CPython converts the source code to byte code and then it is
syntax and is flexible. The programmer has to do less work converted to machine code.
when coding in Python which means the computer has to
Preprints (www.preprints.org) | NOT PEER-REVIEWED | Posted: 21 December 2020 doi:10.20944/preprints202012.0516.v1
Table II.
Comparison between PyPy and CPython (Test Case 2) Best 0.19 0.094 19.54 9.65
Case
PyPy CPython
Fig. 5. Graph between PyPy and CPython speed for test cases 1 & 2
1. Searching Algorithm:
Arranging a given set of data in a predefined manner is sorting Insertion is the process of adding a new element in data
[25]. It can be done using different algorithms, one of which is structure at desired location. It can be added in beginning, end,
bubble sort algorithm. In bubble sorting, first two elements are mid or any other location.
sorted first and then they are compared with the third element
and get sorted and so on [26]. Table V.
Comparison of Time and Memory of Insertion Algorithm
Table IV.
Comparison of Time and Memory of Sorting Algorithm Time in Time in Memory in Memory
Python C++ Python in C++
Time Time Memory Memory (ms) (ms) (Kb) (Kb)
in in C++ in Python in C++
Python (ms) (Kb) (Kb)
(ms) Best 0.024 0.005 7.2 4.01
Case
Worst 1.06 0.011 11.71875 4.04 Average 0.028 0.006 7.31 5.43
Case Case
Deletion is the process in which elements are removed from Python is an advanced language and it is very easy to use.
the data structures and leaving an empty space for new But, along with being easy and having short code, it takes
elements. It can be done from the start of data structure, from more time for execution as compared to C++. C++ converts
the end, mid or other location. whole code into a machine code at once and then executes it.
This method takes less time as compared to Python which
Table VI. converts code line by line to byte code and then converts it to
Comparison of Time and Memory of Deletion Algorithm a machine code. After conversion, it executes the program line
by line. This method takes more time and makes Python slow.
Time in Time in Memory in Memory Moreover, Python utilizes more memory than C++ which also
Python C++ Python in C++ makes it slow. All these arguments are satisfied with the above
(ms) (ms) (Kb) (Kb) charts and graphs.
1. Significance
● Portability
C++ enables its users to run a similar program on different
operating systems making it a portable language.
● Object-Oriented Programming
Since C++ is an object-oriented language, it includes concepts
like structures, inheritance, classes, polymorphism, etc. This
enables programmers to reuse the code easily and better to
understand. Not only this, but it also helps us to deal with the
Fig. 12. Comparison of Memory Consumption of Deletion Algorithm
real-world problems by considering real-world things as an
object.
● Memory Management
C++ provides whole control of memory to the programmer. It
can have its pros and cons, either way, you take it, here the
programmer has the whole command whether to clear past
memory or to save it, the work of the garbage collector is done
by the programmer itself. By using dynamic memory
allocation with the help of pointers the memory management
took place.
● Compatibility with C
C++ is way more compatible with C language. A person with
the basics of the C language can easily start coding in C++. An
Fig. 13. Comparison of Time Utilization of Deletion Algorithm error free code of the C language can easily be run in the
compiler of C++.
Preprints (www.preprints.org) | NOT PEER-REVIEWED | Posted: 21 December 2020 doi:10.20944/preprints202012.0516.v1
● Scalability ● Portability
Basically, the ability to scale a program is known as Just like C++, Python is platform independent. You only need
scalability. So, in C++ we can run either small or big to write the code once and run it anywhere you desire like any
programs. Code of any size, in C++ compilers, is runnable. platform you want just make sure that code is error-free.
● Multi-paradigm ● Scalable
The term ‘Paradigm’ refers to logics, structures, etc. which is It is scalable too. Any size of code either large or small, either
basically a style to represent a code. Hence, C++ is a of a single line would be runnable in Python.
multi-paradigm language because it can be represented into
various styles. ● Vast Standard Library
The standard library in Python is massive, the functions a
2. Issues person can be in need of, all can be easily found in Python’s
library. This is a great advantage to Python’s users.
● Complex Syntax
In comparison to other languages like Python, etc. the syntax ● Productivity Improvement
of C++ is way more complex and lengthier. As Python is easy to understand so the programmer focuses
more on his productivity instead of checking the syntax errors
● Security Issues and managing syntax issues. They write less code, and more
Though C++ is the best language of object-oriented functions are being performed which avoids complexity and
programming as it has objects but due to global variables, code is manageable through which the rate of productivity is
pointers, and public specifiers, security issues still exist. increased.
Python. It is better for newcomers in terms of its easy-to-learn, But for speedy software and better performance like operating
and simple syntax. Furthermore, Web designing and systems, gaming applications, one must consider C++.
backend-development are done with ease in python. Whereas
C++ is not a very good choice for web development of any IX. REFERENCES
type.
[1] Z. Alomari, O. E. Halimi, K. Sivaprasad, and C. Pandit,
Python also leads to data analysis and machine learning. “Comparative studies of six programming languages,”
While comparatively, C++ for ML is neither a good option. If 2015.
we think of simplicity, Python is easier regarding every aspect
and when it comes to Artificial Intelligence and Machine [2] K. Stefanoski, A. Karadimche, and I. Dimitrievski,
Learning there is no other language better than Python. A “PERFORMANCE COMPARISON OF C++ AND
beginner could have a better understanding and can get JAVASCRIPT (NODE.JS – V8 ENGINE),” 2019.
command of this particular language easily because of its
English-like syntax. [3] J. Tait, T. Ripke, L. Roger and T. Matsuo, "Comparing
Python and C++ Efficiency Through Sorting," 2018
VIII. CONCLUSION International Conference on Computational Science and
Computational Intelligence (CSCI), Las Vegas, NV, USA,
In this paper, we made a comparison between Python and 2018, pp. 864-871, doi: 10.1109/CSCI46756.2018.00172.
C++ as these are the two most popular languages in today’s
era. We tried to figure out which language is better in terms [4] M. Ateeq, H. Habib, A. Umer and M. Rehman, "C++ or
of time and memory. First, we discussed how both the Python? Which One to Begin with: A Learner's
languages manage their memory. Discussion showed that C++ Perspective," 2014 International Conference on Teaching
handles memory efficiently. It permits dynamic memory and Learning in Computing and Engineering (LaTiCE),
allocation and allows the programmer to have full control over Kuching, Malaysia, 2014 pp. 64-69. doi:
the memory. A programmer can be able to allocate and 10.1109/LaTiCE.2014.20
deallocate memory whenever he wants. On the other hand,
Python has a garbage collector that is handled by Python . Ashraf, “Introduction” in How to program in C++ with
[5] Z
Runtime Environment (PRE) which collects the memory 100 examples, ( volume-I), 2016, ch.1, pp.1.
which is not going to be used in the future with the help of
reference count. It reduces the work of the programmer but [6] H. E. Ahmed, “Evaluation of C++ as object-oriented
increases the work of the interpreter. programing language compared to Java,” 2018.
Then we examine time consumption by both the languages. . J. Humer and E. C. Foster. “A COMPARATIVE
[7] S
C++ is a statically typed compiled language which is the main ANALYSIS OF THE C++, JAVA, AND PYTHON
reason for its performance efficiency. On the other hand, a LANGUAGES.”, 2014.
Python interpreter takes time to translate the source code into
bytecode and then into machine code. Other than that, Python . T. Bukie, C. L. Udeze, I. O. Obono, and E. B. Edim,
[8] P
works on dynamic typing and solves all the type conversion “Comparative Analysis of Compiler Performances and
issues at run time which also makes it slow. Program Efficiency.”, 2019.
Furthermore, we compared both the languages on the basis [9] W. Wolf, “Programs” in High-Performance Embedded
of sorting, searching, insertion and deletion algorithms on Computing - Architectures, Applications, and
array data structure. We tested their best, worst and average Methodologies, 2nd ed., 2014, ch. 3, pp. 170.
case complexities in terms of time and space. We used
Pycharm for testing Python code and Visual Studio for C++. It [10] G. V. Umoh., “MEMORY MANAGEMENT IN
was evident from the graphs that Python cannot compete with COMPUTER SYSTEM.”, 2014
C++ when it comes to memory and performance but when
their simplicity in writing, understanding, and learning code [11] G. K. Sengottaiyan, “MEMORY MANAGEMENT IN
was discussed, it was concluded that Python is a very powerful C++ AND JAVA.” International Journal Of Engineering
tool for beginners and for coding in less time, but for larger And Computer Science, 2015.
projects that need to complete processing really quick C++ is
suitable. [12] P. Irabashetti and N. Patil, “Dynamic Memory
Allocation: Role in Memory Management,” International
In short, this paper concluded that both the languages hold Journal of Current Engineering and Technology, 2014.
their own importance. Beginners should prefer Python because
of its syntax simplicity, readability, portability and scalability
and avoid C++ as it is a complex language and hard to learn.
Preprints (www.preprints.org) | NOT PEER-REVIEWED | Posted: 21 December 2020 doi:10.20944/preprints202012.0516.v1
[13] R. v. Hattem, "Performance – Tracking and Reducing [25] P. Kunjwal, “BUBBLE SORT,” 2015.
Your Memory and CPU Usage" in Mastering Python,
April 2016, ch. 12, pp. 378-,379 [26] H. Rohil and Manisha, “Run Time Bubble Sort – An
Enhancement of Bubble Sort,” 2014.
[14] S. Romanazzi, “From Manual Memory Management to
Garbage Collection”, 2018. [27] A. Golubin, “Memory management in Python.”
https://rushter.com/blog/python-memory-managment/.
[15] R. v. Hattem, "Performance – Tracking and Reducing
Your Memory and CPU Usage" in Mastering Python, X. BIBLIOGRAPHY
April 2016, ch. 12, pp. 375
Farzeen Zehra is an undergraduate student of Software
[16] W. Wolf, “Programs” in High-Performance Embedded Engineering at NED University of Engineering and
Computing - Architectures, Applications, and Technology. She completed her Matriculation with A+ and got
Methodologies, 2nd ed., 2014, ch. 3, pp. 185. 10th position in Intermediate from Karachi Board. She has a
keen interest in programming and aims to become a web
[17] D. Rassokhin, “The C++ programming language in developer in the future.
cheminformatics and computational chemistry.” Journal of
Cheminformatics, 2020. Darakhshan is an undergraduate student of Software
Engineering at NED University Of Engineering and
[18] K. R. Srinath, "Python – The Fastest Growing Technology. She got 8th position in Intermediate from
Programming Language", 2017. Karachi board. She always wants to learn new stuff as she
possesses a keen interest in front-end web development. Apart
[19] R. v. Hattem, "Decorators – Enabling Code Reuse by from this, she also desires to become a graphic designer.
Decorating" in Mastering Python, April 2016, ch. 5, pp.
130 Maha Javed is a student at NED University of Engineering
and Technology studying Software Engineering. She got her
[20] R. v. Hattem, "Async IO – Multithreading without Matriculation degree from Federal Board with A+ and
Threads" in Mastering Python, April 2016, ch. 7, pp. 176 completed Intermediate from Karachi Board also with A+.
Being a software developer is her dream and she works hard to
[21] K. R. Srinath, "Python – The Fastest Growing fulfill her dream.
Programming Language", 2017.
Maria Pasha completed her secondary school in
[22] R. v. Hattem, "Performance – Tracking and Reducing Pre-Engineering and is now an undergraduate student at NED
Your Memory and CPU Usage" in Mastering Python, University of Engineering and Technology pursuing Software
April 2016, ch. 5, pp. 346 Engineering. She has experience in coding in Python, C#, and
C++. Maria got a keen interest in Mathematics and art and
[23] M. Joseph and P. Keshwani, “Comparison Between designing but due to some circumstances, she ended up
Linear Search and Binary Search Algorithms”, 2018. studying software engineering. She now aims to develop an
interest in programming.
[24] A. R. Chadha, R. Misal, and T. Mokashi, “Modified
Binary Search Algorithm.”, International Journal of
Applied Information Systems, 2014.