views:

75

answers:

2

without using GroupJoin:

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;

using GroupJoin:

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 {}) };

Which of these two pieces is more efficient?

A: 

Without testing, you really can't know. As a rule of thumb, anything done in LINQ is slower than the same thing done manually; the extra iterators and delegate invocations do have their costs.

However, for most practical purposes I would consider them equal in performance. If the performance really makes a difference (i.e. you are in a very critical block, or you notice a slowdown), you will definitely want to measure.

Jouni Heikniemi
A: 

Do you really care about this microptimisation? Your code will be marginally faster, but only noticeable when youre dealing with massive numbers.

Crack out reflector and look how groupJoin works

Andrew Bullock
Yes, massive numbers and high frequency of messages is something I deal with. It would be great to know how GroupJoin works. If it uses a nested loop than it is definitely less efficient than the first snippet.
bsnote
reflectttorrrrr, http://tinyurl.com/dhdvf9
Andrew Bullock