- Frugal Cafe
- Posts
- FC20: Need a List<T> replacement?
FC20: Need a List<T> replacement?
No List is perfect, so you need bunch of them
List is a commonly used class. But no list class is perfect for all scenarios, so you may need more list classes, each for its own classes of scenarios. This is similar to a handyman like me having so many different saws, for different materials, different sizes, different usages, different power sources, and different accuracy levels. Yesterday, I ripped three pieces of metal roof panels using a battery powered circular saw with a metal cutting blade.
Let’s add our own first list class. This one is called OpenList:
Here are the differences comparing with List:
API is bare minimal; more can be added when needed.
The OpenList object is smaller; we removed the sync object which is seldomly used.
The three data fields are all protected, instead of private. They’re accessible from derived classes.
GetRef method is added to get reference to an element. This can be very powerful when element type is struct.
The Clear method has an optional argument; you can skip data cleaning in some cases.
Constructor is empty, so this is faster than List constructor.
Minimum allocation is for single element, instead of 4 elements as in List.
Now let’s see what how we could use this:
StringList is derived from OpenList with a single method override for ToString. You can put bunch of strings into it, and call ToString() to generate string concatenation optimally.
Try to do the same thing with List, you will see the big differences. We can also add a Join method.