DEV Community

Discussion on: Not an "Easy" Algorithm: Rotating an Array, Three Ways

 
miketalbot profile image
Mike Talbot ⭐

I guess my point was that the array is a specific data structure, I expect it to be optimised for being an array. If my problem is something that includes a "rotation" then a rolling buffer may well be a better algorithm - requires no shifting, just a very slightly more complicated retrieve operation and then move a head and tail pointer.

For example: if you are constantly inserting all over a list and only rarely retrieving all the items then no contiguous array, no matter how optimised, will be anywhere near the performance of a linked list.

If I want to implement a thing that has the last 100 values in it then shifting an array for every insertion is massively more costly than increment and modulus. Getting a new array with slice is allocating memory every time. It's easy to write the code, but the consequences may be significant under load.