2010-05-18 54 views
1

不使用羣組加入:C#效率羣組加入

var playersDictionary = players.ToDictionary(player => player.Id, 
    element => new PlayerDto { Rounds = new List<RoundDto>() }); 

foreach (var round in rounds) 
{ 
    PlayerDto playerDto; 
    playersDictionary.TryGetValue(round.PlayerId, out playerDto); 

    if (playerDto != null) 
    { 
     playerDto.Rounds.Add(new RoundDto { }); 
    } 
} 

var playerDtoItems = playersDictionary.Values; 

使用羣組加入:

var playerDtoItems = 
    from player in players 
    join round in rounds 
    on player.Id equals round.PlayerId 
    into playerRounds 
    select new PlayerDto { Rounds = playerRounds.Select(playerRound => new RoundDto {}) }; 

這兩個部件的效率更高?

+1

你的意思是高效?如果它有效,它的有效性。 – 2010-05-18 10:04:42

+0

是的,高效。對不起 – 2010-05-18 10:05:55

回答

1

沒有測試,你真的不知道。作爲一個經驗法則,在LINQ中完成的任何事情都比手動完成的任何事情都慢;額外的迭代器和委託調用確實有其成本。

但是,對於大多數實際目的,我會認爲它們在性能上是平等的。如果表現確實有所改變(即你處於一個非常關鍵的環節,或者你注意到放緩),你肯定會想要測量。

0

你真的關心這種微型化嗎?你的代碼會稍微快一點,但只有在處理大量數據時纔會顯着。

裂開反射器,看看groupJoin如何工作

+0

是的,大量的數字和高頻率的信息是我處理的。瞭解GroupJoin的工作方式將會很棒。如果它使用嵌套循環比肯定效率低於第一個片段。 – 2010-05-18 10:33:47

+0

reflectttorrrrr,http://tinyurl.com/dhdvf9 – 2010-05-18 10:49:52