In def enc1 val try return val encode utf-8 except AttributeError retu

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
In [1]: def enc1(val):
...: try:
...: return val.encode('utf-8')
...: except AttributeError:
...: return val
...:
...:
In [2]: def enc2(val):
...: return (val.encode('utf-8') if isinstance(val, unicode) else val)
...:
In [8]: %timeit enc1('asdasd')
100000 loops, best of 3: 2.42 µs per loop
In [9]: %timeit enc1(u'asdasd')
100000 loops, best of 3: 2.27 µs per loop
In [10]: %timeit enc1(datetime.datetime.now())
100000 loops, best of 3: 13.5 µs per loop
In [11]: %timeit enc2('asdasd')
1000000 loops, best of 3: 1.45 µs per loop
In [12]: %timeit enc2(u'asdasd')
100000 loops, best of 3: 2.72 µs per loop
In [13]: %timeit enc2(datetime.datetime.now())
100000 loops, best of 3: 8.84 µs per loop