Search code examples
c#optimization

Will the compiler optimize away creating this list twice?


public SharpQuery Add(params HtmlNode[] elements)
{
    var nodes = new List<HtmlNode>(_context.Count + elements.Length);
    nodes.AddRange(_context);
    nodes.AddRange(elements);
    return new SharpQuery(nodes, this);
}

public SharpQuery(IEnumerable<HtmlNode> nodes, SharpQuery previous = null)
{
    if (nodes == null) throw new ArgumentNullException("nodes");
    _previous = previous;
    _context = new List<HtmlNode>(nodes);
}

I've got a whole bunch of functions that create a new List<T>, add a bunch of nodes to it, then pass it off to that constructor, which takes the list, and creates yet another new list with it.

Is the compiler smart enough to figure out it doesn't really need to create the list twice?


Solution

  • It isn't a case of being "smart enough" - the compiler does what it is told; you are telling it to create multiple lists: it will create multiple lists.

    However, since you release them promptly they should get collected fairly cleanly, hopefully gen-0. So unless you are doing this in a tight loop, I wouldn't get too excited about it.

    If you want to avoid the lists, you might consider LINQ Concat, which allows you to append sequences without any extra lists / collections / etc.