More efficient to convert string to int or inverse?

int, performance, python, string, type-conversion

Solution

$ python -m timeit "int('92184') == 92184"
1000000 loops, best of 3: 0.482 usec per loop
$ python -m timeit "str(92184) == '92184'"
1000000 loops, best of 3: 0.241 usec per loop

There you go, you should convert ints to strings and compare. Note that this just works if you want to see if they're equal. If you mean to find out which is larger, this won't work, and you should convert to `int`.

Expanding on the above test by pre-generating 1000 random numbers between -1'000'000 and 1'000'000 gives about the same result: 579 usec when using `int` vs. 336 usec when using `str`.

Note that this is very likely premature optimization, as noted in comments. This means that you should think first about other considerations that might influence the way you code, like readability and functionality, and when your script is complete, if it is slow, use a profiler and figure out where you should focus your optimization efforts.

Problem

I'm currently writing a script, which at some point needs to compare numbers provided to the script by two different sources/inputs. One source provides the numbers as integers and one source provides them as strings. I need to compare them, so I need to use either `str()` on the integers or `int()` on the strings. Assuming the amount of conversions would be equal, would it be more efficient to convert the strings into integers or vice versa?

Original source