.NET9 PreView2发布了,它的CLR方面主要有两个重磅功能
下面分别看下?
1.环路优化
这种优化实际上是一种for循环叠加态的优化,for循环叠加计算的过程中,会对其中部分变量进行感应。比如循环中放置0扩展(第一个索引为0),这种优化灵感来源于LLVM标量演化。下面看例子,说明下这个优化:
[MethodImpl(MethodImplOptions.NoInlining)]
static int Foo(int[] arr)
{
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
return sum;
}
未优化前:
G_M8112_IG01:
sub rsp, 40
;; size=4 bbWeight=1 PerfScore 0.25
G_M8112_IG02:
xor eax, eax
xor edx, edx
mov r8d, dword ptr [rcx+0x08]
test r8d, r8d
jle SHORT G_M8112_IG04
align [0 bytes for IG03]
;; size=13 bbWeight=1 PerfScore 3.75
G_M8112_IG03:
mov r10d, edx
add eax, dword ptr [rcx+4*r10+0x10]
inc edx
cmp r8d, edx
jg SHORT G_M8112_IG03
;; size=15 bbWeight=4 PerfScore 19.00
G_M8112_IG04:
add rsp, 40
ret
;; size=5 bbWeight=1 PerfScore 1.25
; Total bytes of code 37, prolog size 4, PerfScore 24.25,
instruction count 14, allocated bytes for code 37
(MethodHash=d1cce04f) for method ConsoleApp34.Program:Foo(int[])
:int (FullOpts)
; ============================================================
未优化前37字节,优化后:
G_M8112_IG01: ;; offset=0x0000
sub rsp, 40
;; size=4 bbWeight=1 PerfScore 0.25
G_M8112_IG02: ;; offset=0x0004
xor eax, eax
mov edx, dword ptr [rcx+0x08]
test edx, edx
jle SHORT G_M8112_IG04
xor r8d, r8d
align [0 bytes for IG03]
;; size=12 bbWeight=1 PerfScore 3.75
G_M8112_IG03: ;; offset=0x0010
add eax, dword ptr [rcx+4*r8+0x10]
inc r8d
cmp edx, r8d
jg SHORT G_M8112_IG03
;; size=13 bbWeight=4 PerfScore 18.00
G_M8112_IG04: ;; offset=0x001D
add rsp, 40
ret
;; size=5 bbWeight=1 PerfScore 1.25
; Total bytes of code 34, prolog size 4, PerfScore 23.25,
instruction count 13, allocated bytes for code 34
(MethodHash=d1cce04f) for method ConsoleApp34.Program:Foo(int[])
:int (FullOpts)
优化后34字节,减少了3字节,优化的指令如下,刚好三字节。这里的优化点是减却寄存器置零或者赋值(称之为放置0扩展),进行共用。
mov 41 89 d2 r10d, edx
这种优化,需要了解一些知识点。假如一个类成员被多个线程访问,一般的访问的时候会设置锁,以避免数据干扰。但是,这同时也产生性能问题。为了提高性能,可以把这个类成员放到线程本地存储(TLS)当中,访问的时候直接去线程本地存储获取,这样极大提高了性能。
但是这还不够,我们需要把访问类成员的代码进行内联。进一步提高性能,不然怎么能叫极致性能优化呢?
代码:
: 90000000 adrp x0, 0 <System_Console_System_ConsoleKeyInfo____GetFieldHelper>
5a2f0: R_AARCH64_TLSDESC_ADR_PAGE21 tls_InlinedThreadStatics
5a2f4: 91000000 add x0, x0, #0x0
5a2f4: R_AARCH64_TLSDESC_ADD_LO12 tls_InlinedThreadStatics
5a2f8: d53bd041 mrs x1, tpidr_el0
5a2fc: f9400002 ldr x2, [x0]
5a2fc: R_AARCH64_TLSDESC_LD64_LO12 tls_InlinedThreadStatics
5a300: d63f0040 blr x2
5a300: R_AARCH64_TLSDESC_CALL tls_InlinedThreadStatics
5a304: 8b000020 add x0, x1, x0
5a308: f9400013 ldr x19, [x0]
一般来说,确定对象的类型需要调用运行时。这会带来一些性能上的损失,也就是说当进行类型检查的时候,运行时为了确保类型正确性,必须进行检查。通过.NET8里面启用的PGO,如果在PGO里面能够确定对象是某个类型,JIT就会用一个快速路径编码,以比较快速的方式进行类型检查。并且在必要的时候退回到慢速路径(常规检查)
bool IsList<T>(IEnumerable<T> source) => source is IList<T>;
如果PGO检测到source总是数组,则会快速路径返回true,否则慢速路径进行检测
if (source is int[])
{
return true;
}
else
{
return slow_path(); // Let the runtime figure it out
}
.NET9 Pre2支持了一种新的实现,利用JIT在Arm64上操作寄存器的加载和存储的能力。简单点来说,就是用SEE,YMM等一次性操控32字节或者64字节的寄存器处理更大量的数据,提升性能。