Reputation: 3092
Recently I have seen a colleague use FirstOrDefault()
when interacting with a Stack instead of Peek()
.
It had never crossed my mind to use an extension method instead of the built-in Peek()
, and I'm wondering what are the implications / differences between the two.
Is one recommended over the other ? Looking with ildasm.exe didn't teach me anything useful.
Upvotes: 3
Views: 1372
Reputation: 405
To quote from MSDn https://msdn.microsoft.com/en-us/library/system.collections.stack.peek%28v=vs.110%29.aspx
Firstly
Peek() is an O(1) operation
FirstOrDefault() works as follows according to Reflector and is a more expensive operation.
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
IList<TSource> list = source as IList<TSource>;
if (list != null)
{
if (list.Count > 0)
{
return list[0];
}
}
else
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
return enumerator.Current;
}
}
}
return default(TSource);
}
Secondly,
Peek errors out at an empty stack, FirstOrDefault returns a null value though First() would also error out.
Upvotes: 2
Reputation: 203844
FirstOrDefault
will return the default value for T
if the stack is empty; Peek
will throw.
That's about it as far as functional changes. FirstOrDefault
adds a few layers of indirection, creating an enumerable/enumerator object (which will eventually need to be disposed of), computing whether there are more items, fetching the first item through the enumerable, and then returning it, rather than having the stack itself do only the necessary operations. While this is technically more work, it's highly unlikely for that to be enough to matter in the vast majority of situations.
Upvotes: 8