I have a series of values in a file and I'm iterating on them. Is it faster to run:
if FTB == "0":
do something
or
if int(FTB) > 0:
do something
I have a series of values in a file and I'm iterating on them. Is it faster to run:
if FTB == "0":
do something
or
if int(FTB) > 0:
do something
Simply using the %timeit
function in IPython:
FTB = 0
%timeit if FTB == 0: pass
10000000 loops, best of 3: 47 ns per loop
FTB = '0'
%timeit if int(FTB) == 0: pass
The slowest run took 9.47 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 231 ns per loop
If you're planning to convert string -> integer on-the-fly using int()
, then it looks like you're losing out on (relatively) quite a bit of speed. Comparisons involving FTB
as a int
to begin with are almost 80% faster than comparisons coercing a string FTB
to integer.
Perhaps your original question was whether simply comparing already-typed objects (like something already an int
or str
and not needing type conversion) was different, speed-wise, in the case of strings and integers. In that case, for completeness:
FTB = '0'
%timeit if FTB == '0': pass
10000000 loops, best of 3: 49.9 ns per loop
FTB = 0
%timeit if str(FTB) == '0': pass
The slowest run took 8.62 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 233 ns per loop
More sampling may be required, but naively it's tough to say there's a significant speed difference comparing str
to str
versus int
to int
. The biggest cost is the cost of calling either the int()
or str()
function to change types.
I am late for the party but here is a simple code that shows that there is almost no difference in python.
Also what may comes to my mind is that integers are limited by the lengt while a string can be any size (until you are out of memory) that's why I am increasing the size.
import time
theinteger = 2147483647
thestring = "2147483647"
stringtime = []
integertime = []
for i in range(0,99999):
t0 = time.time()
if thestring == "2147483647":
print("hello")
t1 = time.time();
stringtime.append(t1 - t0)
t0 = time.time()
if theinteger == 2147483647:
print("hello")
t1 = time.time();
integertime.append(t1 - t0)
theinteger = theinteger + 1;
thestring = str(theinteger)
print("time for string: " + str(sum(stringtime)/len(stringtime)))
print("time for integer: " + str(sum(integertime)/len(integertime)))
Integers are faster to compare because on the CPU it is just one operation. Strings are a representation of an array of characters. To compare a String you have to compare earch item in the array until you find a difference. So this are much more operations to compare the whole String. But the difference is in the range of a couple of nano seconds.