-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Use Array.Fill in Enumerable.Repeat.ToArray #16122
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Less duplication makes me happy. Thanks.
@@ -79,10 +79,7 @@ public TResult[] ToArray() | |||
TResult[] array = new TResult[_count]; | |||
if (_current != null) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@jkotas, is there any efficient and built-in mechanism for checking whether a value is default(TResult)? This check will handle reference types; I'm wondering if there's something that would more generally help with any type.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
System.Runtime.CompilerServices.RuntimeHelpers.Equals(_current, default(TResult))
is identity-equality for reference types, internal representation equality for value types, ignoring all Equals
and ==
overrides.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
But unless there's special recognition of it by the JIT (?), it'll box both value type arguments. Hence the "efficient" part of my question.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@JonHanna That is not particularly efficient though because structs will be boxed and a call will be made. By contrast _current != null
has non-existent overhead for value types because it's eliminated by the JIT. (edit: beaten by @stephentoub)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, it'll box. And now I think about it, I wrote that skip on null, and that's precisely why I didn't test for default generally. I'd certainly love to learn of a non-boxing mechanism.
* Use Array.Fill in Enumerable.Repeat.ToArray Commit migrated from dotnet/corefx@28ffdd6
As the title says. Currently the implementation is the same (using a for-loop) and there's no difference, but in the future it could possibly be optimized by e.g. implementing it natively for reference types to avoid the checks to account for covariant arrays on every store.
/cc @JonHanna @stephentoub @VSadov