Sequenced Collections, Look before you leap

 I have been giving myself a refresher on Java Collections APIs as part of preparation for coding interviews. It's not all reading dry documentation, as we now have podcasts, youtube videos and all manner of consumable media available to consume.

On one particular podcast episode I heard about Sequenced Collections, which was something that was introduced with Java 21 a couple of years ago.

An example of some functionality introduced by Sequenced Collections is the option to obtain a reversed view of a collection. The key word to pay attention to there is, "view".

So, if we take an ArrayList and call reversed() what we get back will be a SequencedCollection of the original ArrayList. As part of the SequencedCollection we can then call addLast(e) to add the specified object, e, onto the end of the collection.

The gotcha

If the ArrayList contains many objects then we will be faced with the performance overhead of adjusting the location offset of each individual existing entry, as behind the scenes the implementation is still the original ArrayList, and that does not offer good performance for inserting items at the start.

So, just like any other API, be careful how you approach methods that seem to be offering a more convenient way of working - there can be a hidden cost to the untrained eye.

 

Another consideration, for really optimal performance

I won't claim credit for this, as it was mentioned on the podcast... ( https://youtu.be/gTBb7LxTBbE?si=AvuwcUSl5XGTKczB )

When we iterate through a data structure we can benefit from CPU cache lines as the processor can pre-fetch data around the location in memory - that's not necessarily going to be the case if our iteration is in a reversed order.

Comments

Popular posts from this blog

Speeding up Software Builds for Continuous Integration

2022 - A year in review

Running Java with Preview Features in the Cloud - Part One