简体   繁体   中英

Linq to objects multiple statements vs. single statement

In Linq to objects is there any difference in the execution between this code:

var changedFileIDs = updatedFiles.Where(file => file.CurrentVersion != file.OriginalVersion).Select(file => file.ID);
var changedVaultFiles = filesToUpdate.Where(x => changedFileIDs.Contains(x.ID));
foreach (var file in changedVaultFiles)
{
    Vault.Upload(file);
}

and this code?

var changedVaultFiles = filesToUpdate.Where(x => updatedFiles.Where(file => file.CurrentVersion != file.OriginalVersion).Select(file => file.ID).Contains(x.ID));
foreach (var file in changedVaultFiles)
{
    Vault.Upload(file);
}

No, there is no difference in performance, because one of the features of Linq is deferred execution , in other words, your query is not going to be executed until the query variable is iterated over in a foreach or for , or calling ToList or ToArray extension method. So in your first example your are composing your main query but is not going to be executed until you iterate over it.

You will find in this link more details about how query execution works in LINQ.

Summary of Deferred Execution :

After a LINQ query is created by a user, it is converted to an command tree. A command tree is a representation of a query.The command tree is then executed against the data source when the query variable is iterated over, not when the query variable is created. At query execution time, all query expressions (that is, all components of the query) are evaluated, including those expressions that are used in result materialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM