Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance: (Compare string) vs (convert to int)

Tags:

python

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.

like image 717
Cool Javelin Avatar asked Feb 13 '15 00:02

Cool Javelin


People also ask

Is it faster to compare int or string?

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.

What is the difference between integer comparison and string comparison?

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.

Can string and int be compared?

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

Can you use comparison operators with strings?

The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.


1 Answers

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

like image 130
Padraic Cunningham Avatar answered Sep 29 '22 06:09

Padraic Cunningham