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?
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
intvs. 336 usec when usingstr.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.