It should be noted (for completeness) that with a Garbage Collected language,
the GC can add random timings into the benchmark.
I have also found that when benchmarking, also switch around the order of two
tests within the code, because that also changes things (can trigger the GC
differently, and change your results).
That said, here is my little benchmark test, where I call the two tests in
different orders, and for me I get results where either looping can be faster
or slower than the other (ie, neither wins outright), but of course, YMMV:
import times
const
Sz = 1000
LoopCnt = 500_000
var
ss1: seq[string] = @["the","rain","in","Spain"]
si1: seq[int] = @[]
sf1: seq[float] = @[]
ss2: seq[string] = @["the","rain","in","Spain"]
si2: seq[int] = @[]
sf2: seq[float] = @[]
t0 = epochTime()
proc p1() =
for i in 0..Sz-1:
si1.add(i)
sf1.add(i.float)
for j in 0 .. LoopCnt-1:
for i in 0..Sz-1:
si1[i] += 1
sf1[i] += 1.0
if i < ss1.len:
ss1[i].add($i)
echo "Dur (..) : ", epochTime() - t0
proc p2() =
for i in 0..<Sz:
si2.add(i)
sf2.add(i.float)
for j in 0 ..< LoopCnt:
for i in 0..<Sz:
si2[i] += 1
sf2[i] += 1.0
if i < ss2.len:
ss2[i].add($i)
echo "Dur (..<) : ", epochTime() - t0
proc main() =
t0 = epochTime()
p1()
t0 = epochTime()
p2()
t0 = epochTime()
p2()
t0 = epochTime()
p1()
main()
My sample results:
tst_it.exe
Dur (..) : 2.262003898620606
Dur (..<) : 2.152803897857666
Dur (..<) : 2.230803966522217
Dur (..) : 2.293204069137573
tst_it.exe
Dur (..) : 2.262003898620606
Dur (..<) : 2.293204069137573
Dur (..<) : 2.215204000473023
Dur (..) : 2.340003967285156
tst_it2.exe
Dur (..) : 2.558404445648193
Dur (..<) : 2.995205163955689
Dur (..<) : 2.184003829956055
Dur (..) : 2.184003829956055