This is part 9/17 of my Exploring the .NET CoreFX series.
Using the builder pattern to allow for easier construction of immutable objects is well-known.
The .NET Core’s immutable collections assembly, System.Collections.Immutable
, also uses the builder pattern, but for a slightly different reason: to improve the performance of making many changes to the collection. This is possible because, unlike the immutable collection itself, the builder pattern does not need to maintain the immutable collection’s invariants after each modification. The builder pattern merely needs to reestablish the invariants of the immutable collection upon the publishing of the results.
Consider this code:
|
|
On each iteration of the loop, array
must be a valid ImmutableArray
. This will lead to a large number of reallocations and memory copies in order to maintain this requirement.
However, if the above code were replaced with this, it would be far more efficient:
|
|
This is also the pattern used by String
and StringBuilder
.
The .NET Core also uses a nice trick of separating ImmutableArray.Builder
, an inner class with a substantial amount of code, into its own file by using partial classes:
|
|
Recommendations
- Immutable objects are often highly valuable. Consider making your objects immutable and implementing the builder pattern.