Exploring The Collections of Spring4D: An Overview of Powerful Features

Slide Note
Embed
Share

The Collections of Spring4D is a versatile library that simplifies memory management and offers extensive APIs for working with collections in Delphi. It provides a range of functionalities like aggregate, concatenate, and checking element existence, making it a valuable tool for developers. By leveraging IEnumerable<T> and following best practices, developers can write expressive and optimized code with ease.


Uploaded on Oct 06, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. european conference

  2. The collections of Spring4D

  3. The collections of Spring4D Spring.Collections Interface based Simplifies memory management Can easily returned by functions and passed around Extensive API via IEnumerable<T> Possibility to write more expressive code Replacement for System.Generics.Collections Not 100% compatible (anymore) but easy to adapt

  4. The collections of Spring4D Spring.Collections Always create new collection instances via TCollections.Create TEnumerable.From, etc Avoid directly using the implementing classes Implementation details so they might change You don t optimizations done in the factory methods (more about that later)

  5. The collections of Spring4D IEnumerable<T> The core collection type all other types inherit from it Contains a rich set of methods to work with any collection Represents a non ordered and often not yet materialized readonly collection of elements

  6. The collections of Spring4D IEnumerable<T> Aggregate(const func: Func<T,T,T>): T Accumulates the values in the collection using the passed function using Default(T) as seed All(const predicate: Predicate<T>): Boolean Determines if all items in the collection satisfy the condition Any: Boolean; Any(const predicate: Predicate<T>): Boolean Returns if the collection has any elements (that satisfy the condition)

  7. The collections of Spring4D IEnumerable<T> Concat(const second: IEnumerable<T>): IEnumerable<T> Returns the combination of this and another collection Contains(const value: T): Boolean Contains(const value: T; const comparer: IEqualityComparer<T>): Boolean Contains(const value: T; const comparer: TEqualityComparison<T>): Boolean Determines if the collection contains the specified element

  8. The collections of Spring4D IEnumerable<T> ElementAt(index: Integer): T ElementAtOrDefault(index: Integer): T ElementAtOrDefault(index: Integer; const defaultValue: T): T Returns the element at the given index or a default value

  9. The collections of Spring4D IEnumerable<T> EqualsTo(const values: array of T): Boolean EqualsTo(const values: IEnumerable<T>): Boolean EqualsTo(const values: IEnumerable<T>; const comparer: IEqualityComparer<T>): Boolean Determines whether two sequences are equal by comparing the elements

  10. The collections of Spring4D IEnumerable<T> - First, Last, Single First: T First(const predicate: Predicate<T>): T FirstOrDefault(const defaultValue: T = Default(T)): T FirstOrDefault(const predicate: Predicate<T>; const defaultValue: T = Default(T)): T Returns the first value in the collection or the first that satisfies the condition or a default value. TryGetFirst(out value: T; const predicate: Predicate<T> = nil): Boolean

  11. The collections of Spring4D IEnumerable<T> - Min and Max Min: T Min(const comparer: IComparer<T>): T Min(const comparer: TComparison<T>): T Returns the minimum value in the collection Min(const selector: Func<T, Integer>): Integer Returns the minimum value in the collection using the projection

  12. The collections of Spring4D IEnumerable<T> - Ordered, Reversed, Shuffled Ordered: IEnumerable<T> Ordered(const comparer: IComparer<T>): IEnumerable<T> Returns the elements ordered by its or the passed comparer Shuffled: IEnumerable<T> Returns the elements in a random order Reversed: IEnumerable<T> Returns the elements in opposite order

  13. The collections of Spring4D IEnumerable<T> - Skip and Take Skip(count: Integer): IEnumerable<T> Bypasses the given number of elements and then returns the remaining elements SkipWhile(const predicate: Predicate<T>): IEnumerable<T> SkipWhile(const predicate: Func<T, Integer, Boolean>): IEnumerable<T> Bypasses all elements while the condition is not satisfied and then returns the remaining elements

  14. The collections of Spring4D IEnumerable<T> - Where Where(const predicate: Predicate<T>): IEnumerable<T> Returns elements that satisfy the condition

  15. The collections of Spring4D IEnumerable<T> - properties Comparer: IComparer<T> The comparer that was passed when creating the collection Count: Integer The number of the items in the collection Beware: this might cause a full iteration of the collection! ElementType: PTypeInfo The type of the elements in the collection IsEmpty: Boolean Determines if the collection is empty opposite of Any

  16. The collections of Spring4D IEnumerable<T> - streaming and deferred execution Chaining methods of IEnumerable<T> that return themselves an IEnumerable<T> only materialize as many elements as the operation needs Example: customers.Where( ).Take(10) This only ever runs the filter being passed to Where until 10 items satisfied the condition Deferred execution makes sure that the operation is only executed if the collection is being iterated even if only partially

  17. The collections of Spring4D TEnumerable Provides factory functions to turn arrays or collections into another collection Contains functions that are not possible on IEnumerable<T>

  18. The collections of Spring4D TEnumerable From<T>(const source: TArray<T>): IReadOnlyList<T> From<T>(const source: array of T): IReadOnlyList<T> Returns a read only list that wraps the passed array Select<T, TResult>(const source: IEnumerable<T>; const selector: Func<T, TResult>): IEnumerable<TResult> Applies a transformation on the input collection and returns it as collection of another type

  19. The collections of Spring4D TEnumerable GroupBy<T, TKey>(const source: IEnumerable<T>; const keySelector: Func<T, TKey>): IEnumerable<IGrouping<TKey,T>> Groups the input by the selected key and returns the groups in order of key occurrence SelectMany<T, TResult>(const source: IEnumerable<T>; const selector: Func<T, IEnumerable<TResult>>): IEnumerable<TResult> Flattens the input and combines it into one output collection

  20. The collections of Spring4D ICollection<T> Represents a non ordered collection of elements that can be modified Info: the actual collection implementation might be ordered but this interface does not give any guarantee about that

  21. The collections of Spring4D ICollection<T> - Add and Remove/Extract Add(const item: T): Boolean AddRange(const values: IEnumerable<T>) Remove(const item: T): Boolean RemoveAll(const predicate: Predicate<T>): Integer RemoveRange(const values: IEnumerable<T>): Integer Extract(const item: T): T ExtractAll(const predicate: Predicate<T>): TArray<T> ExtractRange(const values: IEnumerable<T>): Integer

  22. The collections of Spring4D ICollection<T> - Copy, Move CopyTo(var values: TArray<T>; index: Integer) Copies elements from the collection into the array MoveTo(const collection: ICollection<T>): Integer MoveTo(const collection: ICollection<T>; const predicate: Predicate<T>): Integer Moves elements from the collection into another collection Info: internally it does extracting to not interfer with ownsObjects

  23. The collections of Spring4D ICollection<T> - OnChanged OnChanged: ICollectionChangedEvent<T> Get notified of any change happening to the collection

  24. The collections of Spring4D IList<T> Represents an ordered collection of elements that can be modified Unlike ICollection<T> this type gives a guarantee about a fixed order of the items inside the collection and thus allows operations that are index or order based (like Sort or IndexOf)

  25. The collections of Spring4D IList<T> - Add, Insert Add(const item: T): Integer Adds an item and returns its index in the collection Insert(index: Integer; const item: T); InsertRange(index: Integer; const values: array of T InsertRange(index: Integer; const values: IEnumerable<T>) Insert one of many items at the given index

  26. The collections of Spring4D IList<T> - Remove, Extract Delete(index: Integer) DeleteRange(index, count: Integer) Delete the item(s) at the given index ExtractAt(index: Integer): T ExtractRange(index, count: Integer): TArray<T> Extract the item(s) at the given index Info: for collections that use ownsObjects the Extract methods detach the returned objects from the collection

  27. The collections of Spring4D IList<T> - Exchange, Move, Reverse, Sort Exchange(index1, index2: Integer) Swaps the two items at the specified indexes Move(currentIndex, newIndex: Integer) Moves an item from one to another index Info: if the new index is past the old the item is actually one further to the right (IndexOf returns the new index) Reverse Reverse(index, count: Integer) Reverses the entire list or a subrange in-place

  28. The collections of Spring4D IList<T> - Sort, IndexOf, LastIndexOf Sort Sort(const comparer: IComparer<T>) Sort(const comparer: IComparer<T>; index, count: Integer) Sorts the entire or a sub range of the list IndexOf(const item: T): Integer IndexOf(const item: T; index: Integer): Integer IndexOf(const item: T; index, count: Integer): Integer Returns the index of the given item using the comparer of the list

  29. The collections of Spring4D ReadOnly vs Immutability Spring4D does not contain immutable collections Most mutable collection types have a read-only version however that offer the same operations except those that change the collection like IReadOnlyList<T> has IndexOf and direct array read access but not Add or Delete Passing collections as IEnumerable<T> or as readonly is suggested when the consuming code should only have read access

  30. The collections of Spring4D IMap<K, V> Represents a base type for associative collection types

  31. The collections of Spring4D IMap<K, V> - Add, Remove Add(const key: TKey; const value: TValue) TryAdd(const key: TKey; const value: TValue): Boolean Adds a key/value type and returns if the operation was successful Remove(const key: TKey): Boolean Remove(const key: TKey; const value: TValue): Boolean Removes a key or a key/value pair and returns if the operation was successful Extract(const key: TKey; const value: TValue): TPair<TKey, TValue> Extracts a key/value pair and returns them as a pair

  32. The collections of Spring4D IMap<K, V> - Contains Contains(const key: TKey; const value: TValue): Boolean Determines if the exact key/value pair is contained in the map ContainsKey(const key: TKey): Boolean Determines if the key is contained in the map ContainsValue(const value: TValue): Boolean Determines if the value is contained in the map Info: maps are very fast for a key lookup but looking up the value usually is an O(n) operation

  33. The collections of Spring4D IDictionary<K, V> The typical hashmap implementation to store key/value pairs the key has to be unique

  34. The collections of Spring4D IDictionary<K, V> - additional methods Extract(const key: TKey): TValue GetValueOrDefault(const key: TKey): TValue GetValueOrDefault(const key: TKey; const defaultValue: TValue): TValue TryExtract(const key: TKey; out value: TValue): Boolean TryGetValue(const key: TKey; out value: TValue): Boolean

  35. The collections of Spring4D IMultiMap<K, V> A hashtable that can contain multiple values per key Like a dictionary<k, list<v>> Multiple implementions that create different kinds of collections for a new key: List multimap the standard implementation. Hashset multimap duplicates of value per key are ignored Treeset multimap duplicates are ignored as well but values are sorted

  36. The collections of Spring4D IMultiMap<K, V> - Add Add(const key: TKey; const value: TValue): Boolean AddRange(const key: TKey; const values: array of TValue) AddRange(const key: TKey; const values: IEnumerable<TValue>) Add one or more values for a key

  37. The collections of Spring4D IMultiMap<K, V> - Get and Extract ExtractValues(const key: TKey): ICollection<TValue> Detaches the collection for the given key TryGetValues(const key: TKey; out values: IReadOnlyCollection<TValue>): Boolean Returns if the key exists and if positive gives its values property Items[const key: TKey]: IReadOnlyCollection<TValue> default Returns the values for a given key Hint: does not fail when the key does not exist but returns an empty collection

  38. The collections of Spring4D IStack<T>, IQueue<T> and IDeque<T> Represents Stack (LIFO) Queue (FIFO) Deque (double ended queue, can add and remove on both sides) Queue and Deque are implemented with a circular array buffer and are available in the default implementation which grows or in versions that return false when full or removing the oldest items.

  39. The collections of Spring4D ISet<T> Represents a bag of unique items Like a dictionary but without a value (just key) Implemented as hashset or as red-black-tree

  40. The collections of Spring4D IMultiSet<T> (planned) Represents a counter of unique items Like a dictionary<T, Integer> Manages a counter for each element

  41. The collections of Spring4D IPriorityQueue<T> (planned) Represents a self organizing queue based on the priority of its items Still in concept phase different implementations are possible

  42. The collections of Spring4D Dictionary what is a hashtable 0 1 2 3 4 Key and Value mapping Values go into an array Peter Paul Bob Hash function to get an array index out of the Key used to do insertions and lookup Dealing with hash collisions when more than one item would go into the same index Creating array or linked list at that index to store more than one item Probing looking for the next free slot Order of items is based on the hash function which is not easily predictable

  43. The collections of Spring4D Dictionary the RTL implementation Storing an array of Key/Value pairs plus the HashCode Doing linear probing if slot is occupied Removal is a bit tricky as gaps need to be filled in order to not break probing (see comment in DoRemove) Iteration order is not intuitive

  44. The collections of Spring4D Structure of the RTL dictionary Index 0 1 2 3 4 5 6 7 Key 'Netherlands' <empty> <empty> 'Poland' 'Italy' <empty> <empty> 'Germany' Value 'Amsterdam' Hashcode a67d4cbd 3. 'Warsaw' 'Rome' 94880bda 1007e1b7 4. 2. 1. 'Berlin' d8b00929

  45. The collections of Spring4D Linear probing Index 0 1 2 3 4 5 6 7 Key 'Netherlands' <empty> <empty> <empty> 'Italy' <empty> <empty> 'Germany' Value 'Amsterdam' 'Rome' 'Berlin'

  46. The collections of Spring4D Deletion Index 0 1 2 3 4 5 6 7 Key 'Netherlands' <empty> <empty> <empty> 'Italy' <empty> <empty> <deleted> Value 'Amsterdam' 'Rome' Looking for Netherlands

  47. The collections of Spring4D Making the dictionary ordered Keep items in insertion order (like in a list where you add/append to the end) Possibilities: Maintain ordered key List (this was done in Spring4D 1.2 in the TOrderedDictionary) Add previous and next pointers to the buckets to maintain order (LinkedHashMap<K,V> from Java) Split content into two arrays (dict in Python 3.6) item array holding the key/value pairs bucket array containing the indexes of entries in the item array "We can solve any problem by introducing an extra level of indirection. (David J. Wheeler)

  48. The collections of Spring4D Structure of the new dictionary Item Index 0 1 2 3 Key Value Hashcode Bucket Index 0 1 2 3 4 5 6 7 Item Index 1 <empty> <empty> 3 2 <empty> 0 <empty> 'Germany' 'Italy' 'Netherlands' 'Poland' 'Berlin' 'Rome' 'Amsterdam' 'Warsaw' d8b00929 1007e1b7 a67d4cbd 94880bda

  49. The collections of Spring4D Software meets hardware CPU Cache (L1 100 times faster than RAM, L2 25 times faster) Every indirection (aka reference or pointer) possibly affects performance Storing data in linear data structures (array) Allocating data from a linear data structure

  50. The collections of Spring4D Performance considerations Store the hash in the items array If hash values differ items cannot be equal (comparing hashes it faster than item comparison) Indirection is affecting performance Solution: using some bytes from the ItemIndex for the HashCode

Related