[Tutor] byte array conversion question
Steven D'Aprano
steve at pearwood.info
Thu Feb 3 12:05:33 CET 2011
Bill Allen wrote:
> I have found that there are a couple of ways to convert a byte array to a
> string in Python. Is there any advantage or disadvantage to either method?
>
> my_bytes = b'this is a test'
>
> str(my_bytes,'utf-8') yields 'this is a test'
> my_bytes.decode('utf-8';) yeilds 'this is a test'
Not so far as I know. The decode method is a *tiny* bit faster:
>>> from timeit import Timer
>>> t1 = Timer("str(my_bytes,'utf-8')", "my_bytes = b'this is a test'")
>>> t2 = Timer("my_bytes.decode('utf-8')", "my_bytes = b'this is a test'")
>>> min(t1.repeat())
0.670975923538208
>>> min(t2.repeat())
0.5184659957885742
Those figures are in seconds, for one million calls. So the actual speed
difference is about 0.1 of a microsecond, almost always too trivial to
care about.
--
Steven
More information about the Tutor
mailing list