Tips and Tricks #68: Freeze Collections for Thread-Safe Read Access

Use FrozenDictionary and FrozenSet for immutable, highly-optimized read-only collections.

Code Snippet

using System.Collections.Frozen;

// Create once at startup
private static readonly FrozenDictionary _lookup = 
    new Dictionary
    {
        ["alpha"] = 1,
        ["beta"] = 2,
        ["gamma"] = 3
    }.ToFrozenDictionary();

// Ultra-fast lookups, no locking needed
public int GetValue(string key) => 
    _lookup.TryGetValue(key, out int val) ? val : -1;

Why This Helps

  • Optimized internal structure for read performance
  • Thread-safe without locks
  • Lower memory overhead than concurrent collections

How to Test

  • Benchmark lookup times vs Dictionary
  • Verify thread safety under concurrent access

When to Use

Configuration data, lookup tables, any collection populated once and read many times.

Performance/Security Notes

Available in .NET 8+. Creation is slower than regular collections but reads are faster.

References


Try this tip in your next project and share your results in the comments!


Discover more from Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.