Hi all: I am new to Stack Overflow and am rather new to python, but I have been writing code for years and would like to know which of the following would be better performance.
Assume I have loaded envioron from os, and the flag in the environment is guaranteed to be either a "0" or "1".
if environ["Flag"] == "1":
do_something
or
if int(environ["Flag"]) == 1:
do something
At first glance, it looks like the conversion to int, then comparison would be slower because of the conversion, however, I know string comparisons can be slow also.
Has anyone ever examined this?
Thanks, Mark.
Generally speaking, it is faster to compare two integers. The ALU (Arithmetic Logic Unit) has comparators that are made to work with bits. Integers are arrays of bits, whereas strings are arrays of characters, and characters arrays of bits.
String comparison: You have to compare each of the digits one by one. This is 10 comparisons, since the integers only differ by the last digit. Integer comparison: You can do this in one comparison, saving 9 comparisons as compared to the String comparison.
You can't compare them if you don't give specific criteria. If you want to compare their integer values, then you should convert the string to integer before comparing as you did with proper error handling (i.e. when the string is not an integer).
The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.
In [44]: timeit int("1") == 1
1000000 loops, best of 3: 380 ns per loop
In [44]: timeit "1" == "1"
10000000 loops, best of 3: 36.5 ns per loop
Casting to int will always be slower which makes perfect sense, you start out with a string then convert to an int instead of just creating a string.
Converting is the most costly part:
In [45]: timeit 1
100000000 loops, best of 3: 11.9 ns per loop
In [46]: timeit "1"
100000000 loops, best of 3: 11 ns per loop
In [47]: timeit int("1")
1000000 loops, best of 3: 366 ns per loop
There is a difference between creating a string using a = "1"
than doing a = 1 b = str(1)
which is where you may have gotten confused`.
In [3]: a = 1
In [4]: timeit str(b)
10000000 loops, best of 3: 135 ns per loop
timed using python2.7, the difference using python 3 is pretty much the same.
The output is from my ipython terminal using the ipython magic timeit function
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