Why does linq search have a huge performance difference when I use a string and an array, especially for big data?

I want to find the student’s name that contains the keywords, first I pass the keywords separated by commas, but I think the search time is too long. But when I convert these keywords into an array, it is really fast. Why does linq search have a huge difference in performance? Is it due to array or linq?

Using a string to search

var keyWord="Lyly,Tom,Jack,Rose"; //and so on,more than 500 names
var student= Context.Students.Where(i => keyWord.Contains(i.Name));//very slow

Using an array to search

var keyWord="Lyly,Tom,Jack,Rose"; //and so on,more than 500 names
 var keyWordArray=keyWord.split(',');
var student= Context.Students.Where(i => keyWordArray.Contains(i.Name));//fast
+4
source share
2 answers

Yes, this is because of the array. The Linq database provider can convert an array file into a very efficient form.

Namely, in terms of the database

SQL Like, SQL IN. .

SQL Like , .

SQL IN , IN .

, . Linq2Object, , , , , .

Linq2Object performant, HashSet, :

var keyWord = "Lyly,Tom,Jack,Rose";
var keyWordSet = new HashSet<string>(keyWord.split(','));

var students = Context.Students
                .ToList()
                .Where(i => keyWordSet.Contains(i.Name));
+3

, String.Contains LIKE List.Contains IN (, @ChrisEelmaa).

LINQ , , ( ). String.Contains() , -. , List.Contains() , . , , List.Contains() , .

MSDN :

String.Contains()

List.Contains()

+1

All Articles