user1202434
user1202434

Reputation: 2273

Fastest way to check if a string is a substring C#?

I have a need to check if a list of items contains a string...so kind of like the list gets filtered as the user types in a search box. So, on the text changed event, I am checking if the entered text is contained in one of the listox items and filtering out...so something like:

value.Contains(enteredText)

I was wondering if this is the fastest and most efficient way to filter out listbox items?

Is Contains() method the best way to search for substrings in C#?

Upvotes: 3

Views: 3372

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

Although this is not the fastest option globally, it is the fastest one for which you do not need to code anything. It should be sufficient for filtering drop-down items.

For longer texts, you may want to go with the KMP Algorithm, which has a linear timing complexity. Note, however, that it would not make any difference for very short search strings.

For searches that have lots of matches (e.g. ones that you get for the first one to two characters) you may want to precompute a table that maps single letters and letter pairs to the rows in your drop-down list for a much faster look-up at the expense of using more memory (a pretty standard tradeoff in programming in general).

Upvotes: 1

Sam Harwell
Sam Harwell

Reputation: 99889

Contains is one of the cheapest methods in my code completion filtering algorithm (Part 6 #6, where #7 and the fuzzy logic matching described in the footnote are vastly more expensive), which doesn't have problems keeping up with even a fast typing user and thousands of items in the dropdown.

I highly doubt it will cause you problems.

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

I'd say that in all but very exceptional circumstances, it's fast and efficient enough, and even in such exceptional circumstances it's likely to be a purely academical problem. If you use it and come across any bottlenecks in your logic related to this then I'd be surprised, but only then would it be worth looking at, then chances are you'll be looking elsewhere.

Upvotes: 4

Related Questions