Is LINQ faster or more convenient?

Which of these scenarios will be faster?

Scenario 1:

foreach (var file in directory.GetFiles())
{
    if (file.Extension.ToLower() != ".txt" &&
        file.Extension.ToLower() != ".bin")
        continue;

    // Do something cool.
}

Scenario 2:

var files = from file in directory.GetFiles()
                where file.Extension.ToLower() == ".txt" ||
                      file.Extension.ToLower() == ".bin"
                select file;

foreach (var file in files)
{
     // Do something cool.
} 

I know that they are logically the same due to delayed execution, but what will be faster? And why?

+3
source share
4 answers

Faster is usually not a problem in itself, especially in a scenario where there is no significant difference in performance (and in general, if the code is not a bottleneck, it just does not matter). The problem is that it is more readable and more clearly expresses the intention of the code.

, . " ", " , -". , , . , , LINQ . LINQ, , LINQ , , .

LINQ ?

, , LINQ , , , , , , - . , , , , .

, - , ?

, , LINQ . , , .

?

LINQ . . .

+6

GetFiles("*.txt") GetFile("*.bin"), .

LINQ - .

+2

Linq , . , Linq Fold, Map Filter .NET( ). , DRY - . , , . Linq , , , .

, Linq , . , .

+1

I wrote an article on Code Project that compares linq and stored procedures, as well as using compiled linq.

Please take a look.

http://www.codeproject.com/KB/cs/linqsql2.aspx

I understand that you are looking at local file parsing, the article will give you some idea of ​​what is involved and what linq is doing backstage.

0
source

Source: https://habr.com/ru/post/1779235/


All Articles