Using Lazy for adding values to a cache and returning value, is this fine?


Is using Lazy<T> in this manner fine if the indexer is used often, maybe ~50 times a second? I'm wondering if that is resource intensive creating a local Lazy<T> instance like that every time, should I be doing the check for cached values first for a bit longer of code but a bit more efficient in situations like this?

public Spell this[string name] { get { var spell = new Lazy<Spell>(() => { var s = Spell.GetByName(name); CachedSpellRequests.Add(s); return s; }); return KnownSpells.First(s => s.Name == name) ?? CachedSpellRequests.First(x => x.Name == name) ?? spell.Value; } } 

by JacobKemple via /r/csharp

Leave a Reply