Entity Framework: Performance Hack

Today’s one is quick just like the products we’re trying to build. This one might seem super obvious but it’s helpful to keep in mind regardless. When constructing an EF query, .StartsWith() is significantly more performant that .Contains().

So if you’re trying to keep things fast and efficient use StartsWith instead. This does come at the cost functionality and so can’t be used in all cases, but at least for common searches like email address, not having wildcard matching at the start of the query is acceptable if you can get the search done a lot quicker.

In one example at work, we noticed a 16x performance increase by making this one simple change.

Slow Query

    var searchTerm = "Alex";
    var users = DbContext.Users.Where(u => u.Email.Contains(searchTerm)).ToArray();

Fast Query

    var searchTerm = "Alex";
    var users = DbContext.Users.Where(u => u.Email.StartsWith(searchTerm)).ToArray();

Related Articles