正在使用Lazy T对性能不好吗? [英] Is using Lazy<T> bad for performance?
问题描述
最近,我在singelton类中遇到了一些问题,该类懒惰地初始化字典,在该字典中,第二个线程将在实际填充它之前尝试使用它.因此,我通过
Recently I was having some issues with a singelton class that was lazy initializing a dictionary where a second thread would try to use it before it had actually been populated. So I implemented the variable initialization through the Lazy<T>
class.
这是我的代码:
private static Dictionary<string, string> GroupDefaults
{
get { return mGroupDefaults.Value; }
}
private static Lazy<Dictionary<string, string>> mGroupDefaults =
new Lazy<Dictionary<string,string>>(delegate
{
Dictionary<string, string> defaults = new Dictionary<string, string>();
foreach (KeyValuePair<string, UnitGroup> groupDef in Groups)
defaults.Add(groupDef.Key, groupDef.Value.First().Key);
return defaults;
});
这解决了问题,现在我考虑将其作为我的常规做法,在我进行延迟初始化的任何地方使用 Lazy< T>
类,以避免任何可能的线程问题.因此,基本上我想知道这是否是好的/常见的做法?还是会对性能或某些东西产生不利影响?
This fixed the problem and now I am considering making this a regular practice of mine to use the Lazy<T>
class anywhere I do lazy initialization to avoid any possible threading issues. So basically I would like to know if this is good/common practice? Or will it be detremental to performance or something?
推荐答案
在不知道您具有哪种类型的性能约束的情况下很难说,但是根据我的经验,一次性初始化很少会成为瓶颈(因为从定义上讲,只会发生一次.)编写 Lazy< T>
是为了向您提供此确切服务,所以我建议使用它.
It's pretty hard to say without knowing what type of performance constraints you have, but in my experience, one-time initialization is rarely a bottleneck (since by definition it only occurs once.) Lazy<T>
was written to provide you with this exact service, so I would recommend using it.
这篇关于正在使用Lazy T对性能不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!