A nightly reconciliation job that cross-checks incoming orders against a list of active SKUs crept from "instant" to "noticeable," and the profiler pointed straight at a line I'd have sworn was free. It was a membership check. One Contains . The kind of thing you write without thinking because it reads like plain English: is this SKU allowed?
var allowed = GetActiveSkus (); // a List<Sku> foreach ( var order in incoming ) if ( allowed . Contains ( order . Sku )) keep . Add ( order );
Enter fullscreen mode
Exit fullscreen mode
Reads fine. Does the right thing. And on a list of a few thousand SKUs with a hundred thousand orders flowing through, it was doing an absurd amount of work I never asked for.
The thing I forgot is what List<T>.Contains actually does. It has no index and no shortcut. It starts at the front and compares element by element until it finds a match or runs off the end. For an item that's present that's on average half the list.…