String conversion overhead

时间:2016-07-11 20:26:50

标签: python-2.7

This may sound like a stupid question, but I was wondering if python's str()method causes overhead if the input itself is a string?

e.g. I am using redis.get() method to get a value from redis, and I don't know the type beforehand, so I call the str() method on the return value. I could put it in an if-else block and call str() on returned value only if it is not already string type, but is such mechanism already implemented inside str() implementation?

1 个答案:

答案 0 :(得分:0)

str() is a bit faster if you need to convert:

a = 'a'
b = 1

%timeit x = str(a)
1000000 loops, best of 3: 284 ns per loop

%%timeit
if isinstance(a, str):
    x = a
else:
    x = str(a)
1000000 loops, best of 3: 274 ns per loop

%timeit str(b)
1000000 loops, best of 3: 366 ns per loop

%%timeit
if isinstance(b, str):
    x = b
else:
    x = str(b)
1000000 loops, best of 3: 636 ns per loop

and much more elegant and shorter. So go with str().