Open johnynek opened 1 year ago
I like this!
A couple other thoughts:
creating a List
by concatenating to a mutable builder would also be a lot faster since you can just place elements in the Array
. I guess you'd have to allow the last block to be incomplete (needs logic but seems fine ...)
I wonder if it's worth to try to avoid copying the block on the first prepend, optimistically assuming that it will not be prepended more than once. scodec ByteVector
has some optimizations like this for appending:
Perhaps this will serve as inspiration: https://github.com/sageserpent-open/NTestCaseBuilder/blob/master/development/solution/SageSerpent.Infrastructure/ChunkedList.fs ?
It has a rather horrific test too: https://github.com/sageserpent-open/NTestCaseBuilder/blob/master/development/solution/SageSerpent.Infrastructure.Tests/ChunkedListTests.fs
The canonical encoding of list in scala 2 would be:
but this implementation involves a lot of pointer chasing (to iterate N times into the List we need to dereference N times).
We know from work on immutable vectors that having blocks of arrays that we copy on change can give considerable improvements due to cache locality (and fewer derefs).
So one can imagine another list:
or something like this...
The idea is to copy the block on write. Of course,
apply
,map
,foldLeft
,foreach
,iterator
, etc... could be significantly optimized since once you have a handle on the block iterating to the next value will be in cache.With some appropriate benchmarks you could set the size of the block to some optimal value that I bet would be bigger than 1. It could be that this beats naive List in almost all cases, and when the List isn't too large it could compete with Vector (which isn't as fast as List for stack uses).