Search code examples
delphispring4d

Spring4D TMultiMap maintain IEnumerable on the fly


I create a TMultiMap instance (Spring4D Rel 1.2.2) and immediately create an IEnumerable using the Ordered function.

Then I add a few items to the multimap.

When using the IEnumerable created when the multimap was empty, I list all the items and they are well ordered. When I add or remove items later, the same IEnumerable still show all items correctly ordered.

All this is perfect and works very well.

But is this efficient? Is it better to get the IEnumerable after all insertions? If items are removed or added, should the IEnumerable recreated?

If you need it to answer, I can edit my post and add a simple test program showing what I've done.


Solution

  • Judging efficiency is difficult - so I describe how it works internally and you can decide yourself (and actually measure for yourself):

    Implementations for all the IEnumerable returning methods is done similar to how they work in .Net (aka LINQ). They all have something in common though they don't "materialize" the items until you actually iterate them (or call any other method on them that require materialization) but every time they are iterated they are re-materialized. That means every time you get the exact items from the original source unlike if you would at some point put the items into a list and call sort on that - any item that would get added to the multimap after that point will be missing from the list. Not so in the IEnumerable being returned from Ordered.

    That being said - the Ordered method only needs to be called once - but every time you iterate over those items internally it fetches all items from the underlying source (in your case the multimap) and calls TArray.Sort on them.

    If you are looking for the best data structure / collection and need help deciding for a certain case I suggest posting on google groups as it would not fit on SO.