Felipe Ukan
Felipe Ukan

Reputation: 1

Are str() and int() time consuming in python?

I face myself using a lot of this kind of structure:

for node in range(int(self.num_nodes)):
    dists[str(node)] = -1

So, my questions is: what does python(3+) uses when str() or int(), for example, are called? It just casts? It converts? (something else?)

How would you advice me to write this kind of code? Keep in mind that the key for dists must be a str and num_nodes is also a str.

Upvotes: 0

Views: 341

Answers (1)

mgilson
mgilson

Reputation: 309929

How expensive str and int are depend entirely on the objects that you pass to them. Ultimately, they just call the object's __str__ and __int__ hook methods. For most simple objects, these operations should be pretty fast. e.g. to convert a simple string to an integer takes my computer about .5 microseconds:

$python -mtimeit -s 'x="1"' 'int(x)'
1000000 loops, best of 3: 0.479 usec per loop

and the reverse operation only takes a little over .1 microseconds:

$ python -mtimeit -s 'x=1' 'str(x)'
10000000 loops, best of 3: 0.12 usec per loop

however, it's very easy to create pathological objects for which this would be really expensive.

import time
class Argv(object):
    def __str__(self):
        time.sleep(1000)
        return 'ha ha ha!'

Upvotes: 3

Related Questions