Commit 5c17476
authored
Use builder pattern for ImmutableDictionary construction in ProjectItemInstance (dotnet#13673)
## Use builder pattern for ImmutableDictionary construction in
ProjectItemInstance
Two places in `ProjectItemInstance` build `ImmutableDictionary`
instances by feeding data into `SetItems`, which creates intermediate
immutable trees that are immediately discarded. Switch both to use
`ImmutableDictionaryExtensions.EmptyMetadata.ToBuilder()` (or the
existing dictionary's `.ToBuilder()`) to build mutably, then produce one
final immutable dictionary via `ToImmutable()`.
### Change 1: `TranslateWithInterning` deserialization
`TranslateWithInterning` used a lazy LINQ enumerable
(`Enumerable.Range(0, count).Select(...)`) fed into
`EmptyMetadata.SetItems()`, building the immutable dictionary one entry
at a time. Each entry creates a new intermediate dictionary tree, and
the previous tree is discarded. Allocation traces show this path at
**286 MB sampled** (2.9% of total allocations during Visual Studio
solution load).
Switch to `EmptyMetadata.ToBuilder()` with an eager for-loop, then
`ToImmutable()`. This also eliminates the LINQ/closure allocations from
`Enumerable.Range` + `Select`.
### Change 2: `MetadataCollection` multi-definition merge
`MetadataCollection` merged inherited item definitions by calling
`SetItems` in a loop, creating N-1 intermediate immutable trees. Switch
to `.ToBuilder()` on the base dictionary, merge all definitions mutably,
then `ToImmutable()`.
### Before
- Lazy enumerable or loop feeds N entries/definitions into `.SetItems()`
-- N intermediate `ImmutableDictionary` trees
- Each intermediate tree is discarded on the next iteration
### After
- Eager for-loop or merge into a `Builder` (mutable, no intermediate
trees)
- One final dictionary from `Builder.ToImmutable()`
*Cowritten with Copilot*1 file changed
Lines changed: 24 additions & 11 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1255 | 1255 | | |
1256 | 1256 | | |
1257 | 1257 | | |
| 1258 | + | |
| 1259 | + | |
| 1260 | + | |
| 1261 | + | |
1258 | 1262 | | |
1259 | 1263 | | |
1260 | | - | |
| 1264 | + | |
| 1265 | + | |
| 1266 | + | |
| 1267 | + | |
1261 | 1268 | | |
1262 | 1269 | | |
1263 | 1270 | | |
1264 | 1271 | | |
1265 | 1272 | | |
1266 | | - | |
| 1273 | + | |
| 1274 | + | |
| 1275 | + | |
| 1276 | + | |
1267 | 1277 | | |
1268 | 1278 | | |
1269 | | - | |
| 1279 | + | |
1270 | 1280 | | |
1271 | 1281 | | |
1272 | 1282 | | |
| |||
1917 | 1927 | | |
1918 | 1928 | | |
1919 | 1929 | | |
1920 | | - | |
1921 | | - | |
1922 | | - | |
1923 | | - | |
1924 | | - | |
1925 | | - | |
1926 | | - | |
1927 | | - | |
| 1930 | + | |
| 1931 | + | |
| 1932 | + | |
| 1933 | + | |
| 1934 | + | |
| 1935 | + | |
| 1936 | + | |
| 1937 | + | |
| 1938 | + | |
| 1939 | + | |
| 1940 | + | |
1928 | 1941 | | |
1929 | 1942 | | |
1930 | 1943 | | |
| |||
0 commit comments