https://kotlinlang.org logo
c

Ch8n

03/14/2021, 8:32 AM
Hi Guys! I found
elementAt()
 function on collections, I started to wonder which one is better for getting values,
elementAt()
or
get()
.. Found only this line
element at is useful for collections that do not provide indexed access, or are not statically known to provide one.
, so does that mean
elementAt()
is useful for non-index-based collection? like LinkedList? maps? graphs? Even examples show https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/element-at.html arrays and List sample not other once.. is it because there is only list, set, and map in collections of Kotlin?
e

ephemient

03/14/2021, 9:07 AM
Array.get() is O(1) constant time List.get() is usually O(1) constant time (although this is not true for LinkedList, but there's practically no reason to use that) Iterable<T>.elementAt() for other types is a linear walk of the iterator, so it takes O(n) time, and if you're using it while traversing a whole collection, that's O(n²) time so elementAt() may be useful sometimes, but if you're using it repeatedly or with anything other than small indices you should reconsider, IMO
👍 2
c

Ch8n

03/14/2021, 9:34 AM
@ephemient very insight full 🙏
4 Views