what is a kotliny way to generate a list of elemen...
# announcements
p
what is a kotliny way to generate a list of elements given a number of elements? e.g. something like
5.times |x| mylist << x
in ruby
p
(1..5).forEach { num -> }
?
n
List<Int>(5) { it + 1 }
(or
it
, not sure if that Ruby code starts with
0
or
1
p
For fun, I wrote a benchmark test here: https://pl.kotl.in/7GiATHz0A The results are interesting 😯
m
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
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
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
forEach
with
repeat
or a
for
loop.
p
Repeat wins over range! https://pl.kotl.in/Q3kaqNlTt