Beware of the big bad LINQ

Originally posted to Shawn Hargreaves Blog on MSDN, Thursday, July 16, 2009

Pop quiz – given:

    Stack<int> stack;

what is the difference between:

    return stack.Count;

and:

    return stack.Count();

Is it:

  1. No difference: both return the number of elements on the specified stack
  2. The first is a property of Stack<T>, while the second is a LINQ extension method
  3. The first uses 3 IL instructions, while the second uses 34
  4. The first runs in constant time, while the second is O(n)
  5. The second version generates garbage, while the first does not

Answer: all of the above.

The extension methods defined in the System.Linq namespace are tremendously powerful, and can be a thing of beauty when used wisely, but with great power comes great responsibility. I find it a more than a little scary that such a subtle code change can have such dramatic performance implications!

Blog index   -   Back to my homepage