ufcpp-live / UfcppLiveAgenda

@ufcpp live streaming agenda
MIT License
24 stars 2 forks source link

【2/N】 Performance Improvements in .NET 8 #79

Closed ufcpp closed 9 months ago

ufcpp commented 9 months ago

配信URL: https://www.youtube.com/watch?v=0rkkqdACWsc

前回

終わらない配信。

ufcpp-live commented 9 months ago
try
{

}
catch(Exception e)
{
    //throw e; // これやると元の例外のスタックトレース消えるよ
    throw; // これやると元の例外のスタックトレースが保持されるよ
}

static int m(string s)
{
    // ThrowIfNull の方が(きれいというだけじゃなく)パフォーマンスいい
    if (s is null) throw new ArgumentNullException(nameof(s));
    return s.Length;
}

// ThrowIfNull 以前から、dotnet/runtime 内にはこんなメソッド山ほどあった。
static void Throw()
{
    throw new ArgumentNullException();
}
ufcpp-live commented 9 months ago
// 0~299 まではキャッシュ返す。
Console.WriteLine(ReferenceEquals(0.ToString(), 0.ToString()));
Console.WriteLine(ReferenceEquals(9.ToString(), 9.ToString()));

// .NET 7 時点では0~9までだったらしい。
// .NET 8 で299まで。
Console.WriteLine(ReferenceEquals(299.ToString(), 299.ToString()));

// ここから false。
Console.WriteLine(ReferenceEquals(300.ToString(), 300.ToString()));
ufcpp-live commented 9 months ago
using System.Runtime.CompilerServices;

object x = 1; // box
object y = 1; // 別途新たに box

Unsafe.Unbox<int>(x) = 2;

Console.WriteLine(x);
Console.WriteLine(y); // 今、ちゃんと1。Java の Integer みたいに box キャッシュすると2になっちゃうはず
ufcpp-live commented 9 months ago
var x = "abc";

unsafe
{
    fixed (char* p = x)
    {
        p[0] = 'd';
    }
}

Console.WriteLine("abc"); // dbc
// これができちゃうんで、boxed int の Unsafe.Unbox あっても別にキャッシュしてもいいかも?
ufcpp-live commented 9 months ago
using System.Runtime.CompilerServices;

ReadOnlySpan<byte> data = [1, 2, 3, 4];

Unsafe.AsRef(in data[0]) = 5; // これは AccessViolation
ufcpp-live commented 9 months ago
using System.Runtime.CompilerServices;

var x = 299.ToString();

Unsafe.AsRef(in x.GetPinnableReference()) = 'A';

Console.WriteLine(299); // A99

M o d u l e I n i t i a l i z e r

using System.Runtime.CompilerServices;

for (int i = 0; i < 300; ++i)
    Console.WriteLine(i);

class A
{
    [ModuleInitializer]
    public static void Init()
    {
        for (int i = 0; i < 300; ++i)
            Unsafe.AsRef(in i.ToString().GetPinnableReference()) = ' ';
    }
}
ufcpp-live commented 9 months ago
ReadOnlySpan<char> s = "abc\tdef\tghi";
var ranges = (stackalloc Range[5]);
var num = s.Split(ranges, '\t');

foreach (var r in ranges[..num])
{
    var span = s[r];
}