Every time I perform an arthetic operation in python, new number objects are created. Wouldn't it be more efficient for the interpreter to perform arithmetic operations with primitive data types rather than having the overhead of creating objects (even for numbers) for arithmetic operations? Thank you in advance
Yes, it would.
Just like contrived benchmarks prove more or less whatever you want them to prove.
What happens when you add 3 + 23431827340987123049712093874192376491287364912873641298374190234691283764? Well, if you're using primitive types you get all kinds of overflows. If you're using Python objects then it does some long maths, which yeah, is slower than native math, but they're big numbers so you kind of have to deal with that.
Your right, when you use objects, you have a small overhead which deteriorates efficiency.
But numbers are non-mutable and memory allocation is optimized for small numbers: see the article Python integer objects implementation.
Using objects allows the developer to inherit the number classes int
, float
, complex
and add new, specialized methods.
In Python, a type Hierarchy for Numbers is also defined: Number :> Complex :> Real :> Rational :> Integral. That way, you can have features similar to Scheme.
If you need optimization, you can use Cython. It uses the C language to perform optimizations.
On the other hand, you also have the famous NumPy for scientific computing with Python. This library is also compiled in C.
If you really want to play with primitive types, there is an array
standard packages: Efficient arrays of numeric values.
As a conclusion: We agree that Python numbers are not primitive types, but using objects offer many more possibilities without introducing complexity for the developer, and without too much lose of performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With