After some experimentation, I found that Enumerable.Empty<T> always slow when T is a class type; if it is a value type, it is faster, but depends on the size of the structure. I tested the object, string, int, PointF, RectangleF, DateTime, Guid.
After seeing how it is implemented, I tried various alternatives and found some that work fast.
Enumerable.Empty<T> relies on the inner class EmptyEnumerable<TElement> Instance static property .
This property does few things:
- Checks if a private static volatile field is null.
- Assigns an empty array to the field once (only if empty).
- Returns the value of a field.
Then what Enumerable.Empty<T> really does is only return an empty array from T.
Having tried different approaches, I found that slowness is caused by both the volatile property and modifier .
Accepting a static field initialized with T [0] instead of Enumerable.Empty<T> , as
public static readonly T[] EmptyArray = new T[0];
the problem is gone. Please note that readonly modifier is not defining. Having the same static field declared using volatile or accessed via property causes a problem.
Regards, Daniela
Rubidium 37 Nov 28 '14 at 9:30 2014-11-28 09:30
source share