https://kotlinlang.org logo
t

tim

11/03/2020, 10:53 AM
Hello, I have a list with a few thousand entries in it. I need to add an element to the start of the list ... whats the best way to do this? Currently I'm doing this:
Copy code
val list = listOf(2,3,4)
val el = 1
val next = listOf(el) + list
Thoughts?
c

cheapmon

11/03/2020, 11:05 AM
If you intend to do this a lot, you should probably switch to a different datatype to avoid a big number of copies. ArrayDeque is suitable here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-deque/
t

tim

11/03/2020, 11:06 AM
ahh yes thats much closer to what im looking for🙏
really what I want is a LIFO structure... is there something equivalent in the stdlib?
a

Arkadii Ivanov

11/03/2020, 11:32 AM
There is ArrayDeque, will it work for you?
t

tim

11/03/2020, 1:48 PM
I believe so, going to give it a try today
So I did a very brief comparison between list and deque ... it appears that deque is much slower?
c

cheapmon

11/05/2020, 12:23 PM
Your meaurements are off. With a short test I get the following numbers:
Copy code
Elements	     List	   Deque
     100	    13082	    3590
    1000	     8736	    8034
   10000	    48796	   36239
  100000	   360435	  259785
 1000000	  6179680	 3074326
10000000	200453048	49068629
As you can see,
Deque
is a lot more efficient after a certain threshold.