-1

I want to implement two methods: AddPlayers and AddPlayer. Is it better when AddPlayers calls AddPlayer or AddPlayer calls AddPlayers with a single item array? Is there a significant difference in performance and IL output?

// AddPlayers contains the logic
void AddPlayer(Player player)
{
    return AddPlayers(new [] { player });
}

vs

// AddPlayer contains the logic
void AddPlayers(IEnumerable<Player> players)
{
    foreach (var player in players)
    {
        AddPlayer(player);
    } 
}
Konrad
  • 1,529
  • 2
  • 17
  • 32

1 Answers1

4

I'd ask 2 questions:

  1. Which choice results in more readable code?
  2. Will either choice give you an obvious optimization opportunity, based on expected use cases?

    Gnat's right in his comment about micro-optimization but if you're adding 100,000 players at once, you're going to want the logic in AddPlayers (with a bulk insert). You'll also want a comment in AddPlayer warning the developer not to call it in a loop.

In a more typical situation (adding perhaps at most a dozen players at a time) then it likely doesn't matter much which option you choose.

Dan Pichelman
  • 13,773
  • 8
  • 42
  • 73
  • In my opinion 2nd choice. And I think it will be more performant too but it depends – Konrad Dec 06 '18 at 15:34
  • 4
    @Konrad: It depends on whether you measure it or not. – Robert Harvey Dec 06 '18 at 15:37
  • 2
    *"if you're adding 100,000 players at once, you're going to want the logic in AddPlayers (with a bulk insert)"*, in case you know for sure each single call of `AddPlayer` needs some noteable time, because it produces some database insert. If it just adds an object in-memory to a list, there may be no measurable performance difference, however. So you should always measure, at least make a rough estimation. – Doc Brown Dec 06 '18 at 16:46