https://kotlinlang.org logo
#announcements
Title
# announcements
p

projectmoon

06/07/2019, 4:04 PM
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

pavi2410

06/07/2019, 7:03 PM
(1..5).forEach { num -> }
?
n

nkiesel

06/17/2019, 6:31 PM
List<Int>(5) { it + 1 }
(or
it
, not sure if that Ruby code starts with
0
or
1
p

pavi2410

06/17/2019, 6:59 PM
For fun, I wrote a benchmark test here: https://pl.kotl.in/7GiATHz0A The results are interesting 😯
m

Mike

06/17/2019, 7:05 PM
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
forEach
with
repeat
or a
for
loop.
p

pavi2410

06/18/2019, 6:18 PM
Repeat wins over range! https://pl.kotl.in/Q3kaqNlTt
4 Views