Skip to content
This repository has been archived by the owner on Oct 12, 2022. It is now read-only.

Warn for non-IEquatable<> structs #65

Open
edespong opened this issue Dec 11, 2018 · 0 comments
Open

Warn for non-IEquatable<> structs #65

edespong opened this issue Dec 11, 2018 · 0 comments

Comments

@edespong
Copy link
Contributor

When using a custom struct and you do not make it implement IEquatable<T> there are a number of situations where you will end up with heap allocations where you might not expect.

For example, if you use the struct as key in a Dictionary and do not pass in a custom comparer, every lookup will result in boxing. Calling Contains on a List<T> also cause boxing etc.

The reason is that a struct not implementing IEquatable<T> cannot create a good IEqualityComparer<T> and reverts back to ObjectEqualityComparer<T> which results in boxing on every comparison.

There should be at least two possible ways to attack this:

  1. Analyze struct definitions and warn if it does not implement IEquatable<T>
    This would be easy and warns where the fix is most easily made. It will also eliminate all issues for all methods making use of the default comparer. The downside is that it does not, like all other current warnings, actually warn where a heap allocation takes place. Another downside is that when, in the future, where only analyzing hot paths might be the default it is very unlikely that the definition will be marked as a hot path and will therefore be missed.

  2. Analyze known calls to standard framework methods
    Checking calls for non-IEquatable structs for a set of known method should provide a pretty good coverage. This will warn at the call site an thus be included if only hot paths are analyzed.
    This will not solve all issues even for known cases though, because I do not think that it is possible to find out at the call site of a dictionary lookup whether it has a custom comparer or not, in which case it has to be done when the dictionary is created.

I would say that a combination is the best.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant