Performance wise, what would be better?
A list with function to fetch for a certain ID
Copy code
val listOfItems: List<Item> = listOf<Item>
fun getItemWithId(id: String): Item {
return listOfItems.filter { it.id == id }.first()
}
A map of Item per String
Copy code
val mapOfItems: Map<String,Item>
Or any other solution I didn’t think of?
Thanks 🙂
m
mathew murphy
05/01/2020, 9:20 PM
Map should be faster unless the list is very small. If the list is really big you might want to look at something like a trie.
m
marstran
05/01/2020, 9:34 PM
You can use the
find
function, instead of doing filter + first.
marstran
05/01/2020, 9:36 PM
Now, whether you want to want to create a map or use
find
everytime depends on how many times you need to use it. Creating a map has a performance cost up front, but when you have the map it's fast. Using
find
will make you loop through the list every time.
👍 4
t
Thomas
05/01/2020, 10:25 PM
Copy code
return listOfItems.first { <http://it.id|it.id> == id }
s
Sebastien Leclerc Lavallee
05/02/2020, 2:43 AM
Thanks for the answers!
t
Thomas
05/03/2020, 1:48 PM
@Sebastien Leclerc Lavallee you already have the answer, but more generally if you aren't familiar with "big O" notation https://developerlife.com/2018/08/16/algorithms-in-kotlin-1/ looks to be a good introduction. Knowing the space/time complexity of algorithms will help you answer questions like this in the future.