user857990
user857990

Reputation: 1220

More efficient to convert string to int or inverse?

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?

Upvotes: 3

Views: 3379

Answers (3)

Håken Lid
Håken Lid

Reputation: 23064

The fastest in both python 2.7 and python 3.4 seems to be to use printf style formatting to convert int to string.

'%i' % 92184 == '92184'

python3 -m timeit "'%i' % 92184 == '92184'"
10000000 loops, best of 3: 0.0432 usec per loop

python3 -m timeit "int('92184') == 92184"
1000000 loops, best of 3: 0.284 usec per loop

python3 -m timeit "str(92184) == '92184'"
1000000 loops, best of 3: 0.312 usec per loop

python2 -m timeit "'%i' % 92184 == '92184'"
10000000 loops, best of 3: 0.102 usec per loop

python2 -m timeit "str(92184) == '92184'"
1000000 loops, best of 3: 0.287 usec per loop

python2 -m timeit "int('92184') == 92184"
1000000 loops, best of 3: 0.604 usec per loop

Upvotes: 1

Lauritz V. Thaulow
Lauritz V. Thaulow

Reputation: 50995

$ 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.

Upvotes: 10

avillain
avillain

Reputation: 11

I don't really know what you exactly mean by "compare", but if it is not always only strict egality you'd better work with integers. You could need to sort your data or whatever, and it will be easier this way !

Upvotes: 1

Related Questions