Do you know that array.last is 2x slower than array[array.count - 1]?
#Swift
Clarification: I incorrectly used repeatElement() to create an Array here while it returns an instance of 'Repeated' not Array, and the difference is big.
However, the same performance issue can be seen with Arrays too, and even worse (~10x).
But why accessing the last element in Repeated using the subscript is faster? It's because the subscript function is optimized to simply return the repeated value. Whereas 'last' property is implemented in a generic way in BidirectionalCollection, and it's slower for some reason.
The good news is that the difference, in both cases, becomes negligible when the code is compiled in Release mode. I was testing in Debug mode and didn't expect that switching to Release could narrow the gap that much. Lesson learned.
You can follow @Hejazi.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.