前言

本系列的主要目的是告诉大家在遇到性能问题时,有哪些方案可以去优化;并不是要求大家一开始就使用这些方案来提升性能。

在之前几篇文章中,有很多网友就有一些非此即彼的观念,在实际中,处处都是开发效率和性能之间取舍的艺术。《计算机编程艺术》一书中提到过早优化是万恶之源,在进行性能优化时,你必须要问自己几个问题,看需不要进行性能优化。

  • 优化的成本高么?
  • 如果立刻开始优化会带来什么影响?
  • 因为对任务目标的影响或是兴趣等其他原因而关注这个问题?
  • 任务目标影响有多大?
  • 随着硬件性能提升或者框架版本升级,优化的结果会不会过时?
  • 如果不进行优化或延迟优化的进行会带来什么负面的影响?
  • 如果不进行优化或延迟优化,相应的时间或成本可以完成什么事情,是否更有价值?

如果评估下来,还是优化的利大于弊,而且在合理的时间范围内,那么就去做;如果觉得当前应用的QPS不高、用户体验也还好、内存和CPU都有空余,那么就放一放,主要放在二八法则中能为你创建80%价值的事情上。但是大家要记住过早优化是万恶之源不是写垃圾代码的借口

回到正题,在上篇文章《使用结构体替代类》中有写在缓存和大数据量计算时使用结构体有诸多的好处,最后关于计算性能的例子中,我使用的是简单的for循环语句,但是在C#中我们使用LINQ多于使用for循环。有小伙伴就问了两个问题:

  • 平时使用的LINQ对于结构体是值传递还是引用传递?
  • 如果是值传递,那么有没有办法改为引用传递?达到更好性能?

    针对这两个问题特意写一篇回答一下,字数不多,几分钟就能阅读完。

Linq是值传递

在.NET平台上,默认对于值类型的方法传参都是值传递,除非在方法参数上指定ref,才能变为引用传递。

同样,在LINQ实现的WhereSelectTake众多方法中,也没有加入ref关键字,所以在LINQ中全部都是值传递,如果结构体Size大于8byte(当前平台的指针大小),那么在调用方法时,结构体的速度要慢于引用传递的类。

比如我们编写如下代码,使用常见的Linq API进行数据的结构化查询,分别使用结构体和类,看看效果,数组数据量为1w

public class SomeClass
{
public int Value1; public int Value2;
public float Value3; public double Value4;
public string? Value5; public decimal Value6;
public DateTime Value7; public TimeOnly Value8;
public DateOnly Value9;
} public struct SomeStruct
{
public int Value1; public int Value2;
public float Value3; public double Value4;
public string? Value5; public decimal Value6;
public DateTime Value7; public TimeOnly Value8;
public DateOnly Value9;
} [MemoryDiagnoser]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class Benchmark
{
private static readonly SomeClass[] ClassArray;
private static readonly SomeStruct[] StructArray; static Benchmark()
{
var baseTime = DateTime.Now;
ClassArray = new SomeClass[10000];
StructArray = new SomeStruct[10000];
for (int i = 0; i < 10000; i++)
{
var item = new SomeStruct
{
Value1 = i, Value2 = i, Value3 = i,
Value4 = i, Value5 = i.ToString(),
Value6 = i, Value7 = baseTime.AddHours(i),
Value8 = TimeOnly.MinValue, Value9 = DateOnly.MaxValue
};
StructArray[i] = item;
ClassArray[i] = new SomeClass
{
Value1 = i, Value2 = i, Value3 = i,
Value4 = i, Value5 = i.ToString(),
Value6 = i, Value7 = baseTime.AddHours(i),
Value8 = TimeOnly.MinValue, Value9 = DateOnly.MaxValue
};
}
} [Benchmark(Baseline = true)]
public decimal Class()
{
return ClassArray.Where(x => x.Value1 > 5000)
.Where(x => x.Value3 > 5000)
.Where(x => x.Value7 > DateTime.MinValue)
.Where(x => x.Value5 != string.Empty)
.Where(x => x.Value6 > 1)
.Where(x => x.Value8 > TimeOnly.MinValue)
.Where(x => x.Value9 > DateOnly.MinValue)
.Skip(100)
.Take(10000)
.Select(x => x.Value6)
.Sum();
}
[Benchmark]
public decimal Struct()
{
return StructArray.Where(x => x.Value1 > 5000)
.Where(x => x.Value3 > 5000)
.Where(x => x.Value7 > DateTime.MinValue)
.Where(x => x.Value5 != string.Empty)
.Where(x => x.Value6 > 1)
.Where(x => x.Value8 > TimeOnly.MinValue)
.Where(x => x.Value9 > DateOnly.MinValue)
.Skip(100)
.Take(10000)
.Select(x => x.Value6)
.Sum();
}
}

Benchmakr的结果如下,大家看到在速度上有5倍的差距,结构体由于频繁装箱内存分配的也更多。



那么注定没办开开心心的在结构体上用LINQ了吗?那当然不是,引入我们今天要给大家介绍的项目。

使用StructLinq

首先来介绍一下StructLinq,在C#中用结构体实现LINQ,以大幅减少内存分配并提高性能。引入IRefStructEnumerable,以提高元素为胖结构体(胖结构体是指结构体大小大于16Byte)时的性能。

引入StructLinq

这个库已经分发在 NuGet上。可以直接通过下面的命令安装 StructLinq :

PM> Install-Package StructLinq

简单使用

下方就是一个简单的使用,用来求元素和。唯一不同的地方就是需要调用ToStructEnumerable方法。

using StructLinq;

int[] array = new [] {1, 2, 3, 4, 5};

int result = array
.ToStructEnumerable()
.Where(x => (x & 1) == 0, x=>x)
.Select(x => x *2, x => x)
.Sum();

x=>x用于避免装箱(和分配内存),并帮助泛型参数推断。你也可以通过对WhereSelect函数使用结构来提高性能。

性能

所有的跑分结果你可以在这里找到. 举一个例子,下方代码的Linq查询:

   list
.Where(x => (x & 1) == 0)
.Select(x => x * 2)
.Sum();

可以被替换为下面的代码:

  list
.ToStructEnumerable()
.Where(x => (x & 1) == 0)
.Select(x => x * 2)
.Sum();

或者你想零分配内存,可以像下面一样写(类型推断出来,没有装箱):

 list
.ToStructEnumerable()
.Where(x => (x & 1) == 0, x=>x)
.Select(x => x * 2, x=>x)
.Sum(x=>x);

如果想要零分配和更好的性能,可以像下面一样写:

  var where = new WherePredicate();
var select = new SelectFunction();
list
.ToStructEnumerable()
.Where(ref @where, x => x)
.Select(ref @select, x => x, x => x)
.Sum(x => x);

上方各个代码的Benchmark结果如下所示:

BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042
Intel Core i7-8750H CPU 2.20GHz (Coffee Lake), 1 CPU, 12 logical and 6 physical cores
.NET Core SDK=5.0.101
[Host] : .NET Core 5.0.1 (CoreCLR 5.0.120.57516, CoreFX 5.0.120.57516), X64 RyuJIT
DefaultJob : .NET Core 5.0.1 (CoreCLR 5.0.120.57516, CoreFX 5.0.120.57516), X64 RyuJIT
Method Mean Error StdDev Ratio Gen 0 Gen 1 Gen 2 Allocated
LINQ 65.116 μs 0.6153 μs 0.5756 μs 1.00 - - - 152 B
StructLinqWithDelegate 26.146 μs 0.2402 μs 0.2247 μs 0.40 - - - 96 B
StructLinqWithDelegateZeroAlloc 27.854 μs 0.0938 μs 0.0783 μs 0.43 - - - -
StructLinqZeroAlloc 6.872 μs 0.0155 μs 0.0137 μs 0.11 - - - -

StructLinq在这些场景里比默认的LINQ实现快很多。

在上文场景中使用

我们也把上面的示例代码使用StructLinq改写一下。

// 引用类型使用StructLinq
[Benchmark]
public double ClassStructLinq()
{
return ClassArray
.ToStructEnumerable()
.Where(x => x.Value1 > 5000)
.Where(x => x.Value3 > 5000)
.Where(x => x.Value7 > DateTime.MinValue)
.Where(x => x.Value5 != string.Empty)
.Where(x => x.Value6 > 1)
.Where(x => x.Value8 > TimeOnly.MinValue)
.Where(x => x.Value9 > DateOnly.MinValue)
.Skip(100)
.Take(10000)
.Select(x => x.Value4)
.Sum(x => x);
} // 结构体类型使用StructLinq
[Benchmark]
public double StructLinq()
{
return StructArray
.ToStructEnumerable()
.Where(x => x.Value1 > 5000)
.Where(x => x.Value3 > 5000)
.Where(x => x.Value7 > DateTime.MinValue)
.Where(x => x.Value5 != string.Empty)
.Where(x => x.Value6 > 1)
.Where(x => x.Value8 > TimeOnly.MinValue)
.Where(x => x.Value9 > DateOnly.MinValue)
.Skip(100)
.Take(10000)
.Select(x => x.Value4)
.Sum(x => x);
} // 结构体类型 StructLinq 零分配
[Benchmark]
public double StructLinqZeroAlloc()
{
return StructArray
.ToStructEnumerable()
.Where(x => x.Value1 > 5000, x=> x)
.Where(x => x.Value3 > 5000, x => x)
.Where(x => x.Value7 > DateTime.MinValue, x => x)
.Where(x => x.Value5 != string.Empty, x => x)
.Where(x => x.Value6 > 1, x => x)
.Where(x => x.Value8 > TimeOnly.MinValue, x => x)
.Where(x => x.Value9 > DateOnly.MinValue, x => x)
.Skip(100)
.Take(10000)
.Select(x => x.Value4, x => x)
.Sum(x => x);
} // 结构体类型 StructLinq 引用传递
[Benchmark]
public double StructLinqRef()
{
return StructArray
.ToRefStructEnumerable() // 这里使用的是ToRefStructEnumerable
.Where((in SomeStruct x) => x.Value1 > 5000)
.Where((in SomeStruct x) => x.Value3 > 5000)
.Where((in SomeStruct x) => x.Value7 > DateTime.MinValue)
.Where((in SomeStruct x) => x.Value5 != string.Empty)
.Where((in SomeStruct x) => x.Value6 > 1)
.Where((in SomeStruct x) => x.Value8 > TimeOnly.MinValue)
.Where((in SomeStruct x) => x.Value9 > DateOnly.MinValue)
.Skip(100)
.Take(10000)
.Select((in SomeStruct x) => x.Value4)
.Sum(x => x);
} // 结构体类型 StructLinq 引用传递 零分配
[Benchmark]
public double StructLinqRefZeroAlloc()
{
return StructArray
.ToRefStructEnumerable()
.Where((in SomeStruct x) => x.Value1 > 5000, x=> x)
.Where((in SomeStruct x) => x.Value3 > 5000, x=> x)
.Where((in SomeStruct x) => x.Value7 > DateTime.MinValue, x=> x)
.Where((in SomeStruct x) => x.Value5 != string.Empty, x=> x)
.Where((in SomeStruct x) => x.Value6 > 1, x => x)
.Where((in SomeStruct x) => x.Value8 > TimeOnly.MinValue, x=> x)
.Where((in SomeStruct x) => x.Value9 > DateOnly.MinValue, x=> x)
.Skip(100, x => x)
.Take(10000, x => x)
.Select((in SomeStruct x) => x.Value4, x=> x)
.Sum(x => x, x=>x);
} // 结构体 直接for循环
[Benchmark]
public double StructFor()
{
double sum = 0;
int skip = 100;
int take = 10000;
for (int i = 0; i < StructArray.Length; i++)
{
ref var x = ref StructArray[i];
if(x.Value1 <= 5000) continue;
if(x.Value3 <= 5000) continue;
if(x.Value7 <= DateTime.MinValue) continue;
if(x.Value5 == string.Empty) continue;
if(x.Value6 <= 1) continue;
if(x.Value8 <= TimeOnly.MinValue) continue;
if(x.Value9 <= DateOnly.MinValue) continue;
if(i < skip) continue;
if(i >= skip + take) break;
sum += x.Value4;
} return sum;
}

最后的Benchmark结果如下所示。



从以上Benchmark结果可以得出以下结论:

  • 类和结构体都可以使用StructLinq来减少内存分配。
  • 类和结构体使用StructLinq都会导致代码跑的更慢。
  • 结构体类型使用StructLinq的引用传递模式可以获得5倍的性能提升,比引用类型更快。
  • 无论是LINQ还是StructLinq由于本身的复杂性,性能都没有For循环来得快。

总结

在已经用上结构体的高性能场景,其实不建议使用LINQ了,因为LINQ本身它性能就存在瓶颈,它主要就是为了提升开发效率。建议直接使用普通循环。

如果一定要使用,那么建议大于8byte的结构体使用StructLinq引用传递模式(ToRefStructEnumerable),这样可以把普通LINQ结构体的性能提升5倍以上,也能几乎不分配额外的空间。

.NET性能优化-为结构体数组使用StructLinq的更多相关文章

  1. .NET性能优化-使用结构体替代类

    前言 我们知道在C#和Java明显的一个区别就是C#可以自定义值类型,也就是今天的主角struct,我们有了更加方便的class为什么微软还加入了struct呢?这其实就是今天要谈到的一个优化性能的T ...

  2. C#调用C/C++动态库 封送结构体,结构体数组

    一. 结构体的传递 #define JNAAPI extern "C" __declspec(dllexport) // C方式导出函数 typedef struct { int ...

  3. 【C语言入门教程】7.2 结构体数组的定义和引用

    7.2 结构体数组的定义和引用 当需要使用大量的结构体变量时,可使用结构体定义数组,该数组包含与结构体相同的数据结构所组成的连续存储空间.如下例所示: struct student stu_a[50] ...

  4. Delphi结构体数组指针的问题

    //这段代码在Delphi 2007和delphi 7下是可以执行的,所以正确使用结构体数组和指针应该是这样的,已验证 unit Unit1; interface uses Windows, Mess ...

  5. C语言中的结构体,结构体数组

    C语言中的结构体是一个小难点,下面我们详细来讲一下:至于什么是结构体,结构体为什么会产生,我就不说了,原因很简单,但是要注意到是结构体也是连续存储的,但要注意的是结构体里面类型各异,所以必然会产生内存 ...

  6. 结构体数组(C++)

    1.定义结构体数组 和定义结构体变量类似,定义结构体数组时只需声明其为数组即可.如: struct Student{ int num; char name[20]; char sex[5]; int ...

  7. c语言学习之基础知识点介绍(十七):写入读取结构体、数组、结构体数组

    一.结构体的写入和读取 //写入结构体 FILE *fp = fopen("/Users/ios/Desktop/1.data", "w"); if (fp) ...

  8. c语言结构体数组定义的三种方式

    struct dangdang { ]; ]; ]; int num; int bugnum; ]; ]; double RMB; int dangdang;//成员名可以和类名同名 }ddd[];/ ...

  9. C#调用C++DLL传递结构体数组的终极解决方案

    在项目开发时,要调用C++封装的DLL,普通的类型C#上一般都对应,只要用DllImport传入从DLL中引入函数就可以了.但是当传递的是结构体.结构体数组或者结构体指针的时候,就会发现C#上没有类型 ...

随机推荐

  1. 攻防世界NewsCenter

    NewsCenter 打开题目是一个搜索框我们首先尝试一下sql注入 判断了一下是使用''进行包裹的字符型sql注入 然后我们需要判断数据库列数 1' order by 3# 回显正常但by4的时候回 ...

  2. 当心,你搞的Scrum可能是小瀑布

    摘要:有的团队刚接触Scrum,一个问题令他们很困扰:迭代初期开发人员的工作较多,测试人员闲着:迭代末期开发人员闲着,测试人员的工作比较多,怎么解决资源等待的问题呢? 本文分享自华为云社区<当心 ...

  3. 学习HTML5 history API

    html5 在 history 对象上添加几个新的方法.事件.属性,用以增强开发者对于浏览器历史记录的控制.大体上说,新的API可以帮助我们在无刷新的情况下改变浏览器的url,新增或者替换之前的历史记 ...

  4. 前端面试题整理——关于EventLoop(1)

    下面代码输出打印值顺序: async function async1(){ console.log('async1 start'); await async2(); console.log('asyn ...

  5. SecureCRT显示连接失败的原因

    问题描述:连接后像192.168.111.140那样的红色图标 原因:没有开启对应的虚拟机 解决办法:打开对应的虚拟机

  6. Android Studio安装及问题

    安装教程+虚拟机调试:https://blog.csdn.net/y74364/article/details/96121530 gradle下载缓慢解决办法:https://blog.csdn.ne ...

  7. 使用mockjs模拟后端返回的json数据;

    前后端分离开发中最重要的一部就是前后端联调,很多时候后端进度是跟不上前端的,所以需要前端模拟一些数据进行调试,这样前端的进度就可以加快了.后端的小哥哥别打我: 使用mockjs可以很方便的模拟出想要的 ...

  8. YC-Framework版本更新:V1.0.6

    分布式微服务框架:YC-Framework版本更新V1.0.6!!! 本文主要内容: V1.0.6版本更新主要内容 V1.0.6版本更新主要内容介绍 一.V1.0.6版本更新主要内容 1.系统例子覆盖 ...

  9. shiro+springboot分析思路

    文章目录 前言 一.为什么要使用shiro 二.使用步骤 1.如何认证和授权 2.如何获取数据 总结 前言 shiro和spring security等安全框架可以用户管理和权限认证 一.为什么要使用 ...

  10. Mybatis映射文件动态SQL语句-02

    foreach UserMapper.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYP ...