Linq usage & performance
本文目录 7 个章节
Linq usage & performance
创建时间:2021/2/1 12:11
Introduction
LINQ(Language Integrated Query, pronounced “link”), is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages.
LINQ extends the language by the addition of query expressions, which are akin to SQL statements, and can be used to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases, and third-party data sources.
Usage
Demo
string s1 = "Hello ";
string s2 = s1;
s1 += "World";
System.Console.WriteLine(s2);
//Output: Hello
string s1 = "Hello ";
string s2 = s1;
s1 += "World";
System.Console.WriteLine(s2);
//Output: Hello
Advantages
提高可读性(readable )
增加简洁性(concise)
加快开发效率
用法理解
LINQ = 集合 + 操作符 + 具体操作
集合:C# 中的 Array、Dictionary、List、Stack、Queue 都是集合,都是可以用 LINQ 的。
操作符: Where、Select、GroupBy、Distinct 都是操作符。
操作:操作指的是foreach/ForEach/Single/First/ToList/ToDictionary/ToHashSet等等
Performance
SQL-style LINQ queries are a concise, readable way of performing various tasks dealing with all kinds of collections. Surely all that convenience comes with a performance cost to it.
LINQ 在执行过程中会产生一些临时变量,而且会用到委托(lambda 表达式)。使用委托作为条件判定方法,时间开销较高,并且会造成一定的堆内存分配。
string s1 = "Hello ";
string s2 = s1;
s1 += "World";
System.Console.WriteLine(s2);
//Output: Hello
Ref
https://en.wikipedia.org/wiki/Language_Integrated_Query https://zhuanlan.zhihu.com/p/161681422 https://www.jacksondunstan.com/articles/4819