我试图稍微离开LINQ,虽然它总体上非常有用,但有时阅读起来也很困难。
以前我使用LINQ执行连接(完全外连接),但更喜欢使用for / foreach循环进行连接,因为它们更简单。我刚刚将一个LINQ语句(不是PLINQ)转换为嵌套的foreach循环,性能严重下降。以前需要几秒钟,现在需要约一分钟,代码如下所示。
foreach (var p in PortfolioELT)
{
double meanloss;
double expvalue;
double stddevc;
double stddevi;
bool matched = false;
foreach (var a in AccountELT)
{
if (a.eventid == p.eventid)
{ DO SOME MATH HERE <-----
有没有关于以下问题的想法:
- 为什么这比LINQ Join慢?
- 如何加速它?
程序显然达到了它需要达到的目标,但速度太慢。
编辑: 旧代码全文:
public static ConcurrentList<Event> CreateNewELTSUB(IList<Event> AccountELT, IList<Event> PortfolioELT)
{
if (AccountELT == null)
{
return (ConcurrentList<Event>)PortfolioELT;
}
else
{
//Subtract the Account ELT from the Portfolio ELT
var newELT = from p in PortfolioELT
join a in AccountELT
on p.eventid equals a.eventid into g
from e in g.DefaultIfEmpty()
select new
{
EventID = p.eventid,
Rate = p.rate,
meanloss = p.meanloss - (e == null ? 0d : e.meanloss),
expValue = p.expValue - (e == null ? 0d : e.expValue),
stddevc = Math.Sqrt(Math.Pow(p.stddevc, 2) - (e == null ? 0d : Math.Pow(e.stddevc, 2))),
stddevi = Math.Sqrt(Math.Pow(p.stddevi, 2) - (e == null ? 0d : Math.Pow(e.stddevi, 2)))
};
ConcurrentList<Event> list = new ConcurrentList<Event>();
foreach (var x in newELT)
{
list.Add(new Event(x.meanloss, x.EventID, x.expValue, x.Rate, x.stddevc, x.stddevi));
}
return list;
}
}
新代码完整:
public static ConcurrentList<Event> CreateNewELTSUB(IList<Event> AccountELT, IList<Event> PortfolioELT)
{
if (AccountELT == null)
{
return (ConcurrentList<Event>)PortfolioELT;
}
else
{
//Subtract the Account ELT from the Portfolio ELT
ConcurrentList<Event> newlist = new ConcurrentList<Event>();
//Outer Join on Portfolio ELT
foreach (var p in PortfolioELT)
{
double meanloss;
double expvalue;
double stddevc;
double stddevi;
bool matched = false;
foreach (var a in AccountELT)
{
if (a.eventid == p.eventid)
{
matched = true;
meanloss = p.meanloss - a.meanloss;
expvalue = p.expValue - a.expValue;
stddevc = Math.Sqrt((Math.Pow(p.stddevc, 2)) - (Math.Pow(a.stddevc, 2)));
stddevi = Math.Sqrt((Math.Pow(p.stddevi, 2)) - (Math.Pow(a.stddevi, 2)));
newlist.Add(new Event(meanloss, p.eventid, expvalue, p.rate, stddevc, stddevi));
}
else if (a.eventid != p.eventid) //Outer Join on Account
{
newlist.Add(a);
}
}
if (!matched)
{
newlist.Add(p);
}
}
return newlist;
}