Assuming you got similar results (1000, List<Int>(1000) much faster, 1M-> forEach much faster), then definitely agree.
I think we'd all intuitively expect one or the other to be faster...
c
Casey Brooks
06/17/2019, 7:10 PM
Another thing to consider is memory usage.
(1..5).forEach { }
does not keep the entire list in-memory, it is just an iterator, so larger ranges do not take up more memory.
List<Int>(5) { }
holds all elements in memory, and thus cannot be used for really large ranges
n
nkiesel
06/17/2019, 9:00 PM
for starters, you should really use
nanoTime
for micro-benchmarks like this. Not because of the granularity but because that really measures the time the JVM was running instead of elapsed system time. But more to the point, the 2 do something very different: the
repeat
calls a block
n
times and throws away the returned values while the
List(n) { block }
keeps all the values. So why are we comparing the 2? I could see to compare