开发者

C# GroupJoin efficiency

开发者 https://www.devze.com 2022-12-30 10:46 出处:网络
without using GroupJoin: var playersDictionary = players.ToDictionary(player => player.Id, element => new PlayerDto { Rounds = new List<RoundDto>() });

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 (pla开发者_运维问答yerDto != 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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消