Performance wise, what would be better? A list wit...
# announcements
s
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
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
You can use the
find
function, instead of doing filter + first.
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
Copy code
return listOfItems.first { <http://it.id|it.id> == id }
s
Thanks for the answers!
t
@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.
👍 1