Let's say I have a few numeric variables that will be used throughout the code like int and str objects. So I'm wondering, which type should I use to store them?
Here's an example:
class Nums:
a = 1 # stored as int
b = '2' # stored as str
print(int(Nums.b) + 5) # 7
print(str(Nums.a) + 'Hello') # 1Hello
As you can see, there are the two choices of storage and example uses. But the usage won't be so defined like it is here. For example, I will iterate over the class variables and concatenate them all in a string and also compute their product. So should I store them as int and cast to str when I need concatenation or as str and cast them to int before multiplication?
Some brief research using the IPython's %timeit has shown that the performance is about the same, int to str is a tiny bit faster:
In [3]: %timeit int('56')
The slowest run took 12.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 360 ns per loop
In [4]: %timeit str(56)
The slowest run took 8.36 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 353 ns per loop
And I would expect this result, as an str call really just calls the object's __str__ method, while reading a string as a number could be more complicated. Is there any real difference and what's the reason behind it?
I'm talking about Python 3.5 particularly
If your program uses numeric values, you should certainly store them as type int. Numeric types are almost always faster than string types, and even if your use case means the string representation is faster, the other benefits are worth it. To name a few:
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