在以下情况下,linq 技术的效率会降低多少,并且可以进行优化吗?
在以下情况下,linq 技术的效率会降低多少,并且可以进行优化吗?
Linq 技术:
public String FindProviderName(Int32? TrueName)
{
String providerName = (from p in this.Providers
where p.TrueName == TrueName
select p.ProviderName).First().ToString();
return providerName;
}
步行技术:
public String FindProviderName(Int32? TrueName)
{
String providerName = String.Empty;
foreach (IProvider provider in this.Providers)
{
if (provider.TrueName == TrueName)
{
providerName = provider.ProviderName;
break;
}
}
return providerName;
}
How much less efficent would the linq technique be in the following case and could either be optimised?
Linq technique:
public String FindProviderName(Int32? TrueName)
{
String providerName = (from p in this.Providers
where p.TrueName == TrueName
select p.ProviderName).First().ToString();
return providerName;
}
Walking technique:
public String FindProviderName(Int32? TrueName)
{
String providerName = String.Empty;
foreach (IProvider provider in this.Providers)
{
if (provider.TrueName == TrueName)
{
providerName = provider.ProviderName;
break;
}
}
return providerName;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果那是 LINQ 到对象,那么它们都会非常快。如果您想要更快,请考虑使用
Dictionary
并使用TryGetValue(...)
。显然,您需要预先生成字典,也许可以通过 ToDictionary() 来生成。请注意,当没有匹配时,显示的两个示例是不同的;一个投掷;一个返回一个空字符串。此外,无需对字符串调用 ToString()。
重新获得更快的版本(评论);您需要一个字段,
并且在使用之前(或数据更改之后)的某个时刻您需要填充它:
那么您的查找将类似于:
If that is LINQ-to-objects, they'll both be pretty fast. If you want faster, consider a
Dictionary<int,string>
and useTryGetValue(...)
. Obviously you need to pre-generate the dictionary, perhaps via ToDictionary().Note that the two examples shown are different when there is no match; one throws; one returns an empty string. Also, there is no need to call ToString() on a string.
Re the faster version (comments); you need a field,
And at some point prior to use (or after data changes) you need to populate it:
Then your lookup would be like:
你有了代码,如果你想知道它的效率如何,只需测量它即可。
当然,人们经常担心代码的效率,但其实他们不应该担心。可读性不是更重要吗?这是让你减慢速度的代码吗?
话虽这么说,第一个代码可以稍微快一点,如下所示:
第二个代码可以通过使用
for
而不是foreach
来加快速度(如果您的集合类型是 < 但是,这两种优化很可能不会产生任何可测量的效果。
You have the code, if you want to know how efficient it is, just measure it.
Of course, people quite often worry about efficiency of code, when they shouldn't. Isn't readability more important? Is this the code that slows you down?
That being said, the firs code could be made slightly faster like this:
And the second one may be made faster by using
for
instead offoreach
(if your collection type isList<T>
or an array.Both those optimizations most likely won't have any measurable effect, though.