I've been surprised by the results provided by %timeit for these two implementations :
def f1():
s = ''
for i in range(len(values)):
s += str(values[i][0])
s += '\t'
s += str(values[i][1])
s += '\r\n'
return s
and
def f2():
return ''.join((
str(ts) + '\t' + str(v) + '\r\n'
for ts, v in values
))
knowing that values
is a list of approx 2400 tuples. f1()
is the original code I found in a script written by a colleague more used to C/C++ that to Python at the time he wrote it, and f2
is IMHO the more Pythonic style I would have written for the same processing.
I would have expected that f2
being a lot faster that f1
, mainly because f1
uses a lot of concatenations and string re-allocations but it occurs that %timeit
gives the same magnitude order for both ones (approx. 18ns), and more surprisingly, giving f2
1ns faster sometimes 1ns.
What could be the explanation for such a result ?
[EDITED Jul 14] fixed f1 for the str
override by the local variable with the same name. This error was not present in the profiled code however.