---
title: "Linq usage & performance"
author: "Perrin Yong"
author_profile: https://www.pystone.net/profile/
published_by: "Perrin Yong"
canonical: https://www.pystone.net/notes/unity-linq-usage-performance/
type: note
content_role: unspecified
visibility: public
id_stability: rename-stable
source_path: "10-计算机、信息技术与工程/05-游戏图形与运行时/游戏性能优化/Linq usage & performance.md"
content_hash: ed6435c0427cb77bd8f676bfafee9944fb3e59ce306c2339124d080fb8f7a67e
knowledge_version: 224c990773de.5fa8af6e39fa
site_commit: 224c990773de166d23a886306577dd90379529ce
notes_commit: 5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a
---
# 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

```csharp
string s1 = &quot;Hello &quot;;
string s2 = s1;
s1 += &quot;World&quot;;

System.Console.WriteLine(s2);
//Output: Hello

```
```csharp
string s1 = &quot;Hello &quot;;
string s2 = s1;
s1 += &quot;World&quot;;

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 表达式）。使用委托作为条件判定方法，时间开销较高，并且会造成一定的堆内存分配。

```csharp
string s1 = &quot;Hello &quot;;
string s2 = s1;
s1 += &quot;World&quot;;

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>
