illright
illright

Reputation: 4043

Which way of the cast between str and int is faster in Python?

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

Upvotes: 3

Views: 827

Answers (1)

Tim
Tim

Reputation: 3725

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:

  • You get sanity checks for free. If someone tries to shove "five" into your program, if you're storing as integers you'll get an error early. If you're storing as strings, your error may be much harder to reason about.
  • Anyone picking up your program will expect numeric values to be stored as numeric types
  • And again, storing things as numeric types is almost always faster

Upvotes: 1

Related Questions