Edit

Share via


Inefficient List<T>.Find usage

This article describes performance insights when using List<T>.Find.

Cause

List<T>.Find method is resulting in slow performance.

Performance insight description

The List<T>.Find method performs a linear search through the list, resulting in O(n) time complexity for each lookup. This can be inefficient when searching for items frequently or in large lists.

If possible, consider using Dictionary<TKey,TValue> or a HashSet<T>. If you can assign a key or unique property to the value, Dictionary<TKey,TValue> can be used. If you're storing unique values, HashSet<T> can be used. Both of these alternative data structures have an O(1) time complexity for each lookup compared to O(n) in List<T>.Find.

How to investigate a warning

In the CPU Usage tool, click View source code to find where List<T>.Find is used. If possible, refactor code to use an alternative data structure with faster lookups.

See also

Dictionaries in .NET