Cysharp / MagicOnion

Unified Realtime/API framework for .NET platform and Unity.
MIT License
3.89k stars 433 forks source link

Reduce allocation on StreamingHubClient method calls #786

Closed mayuki closed 5 months ago

mayuki commented 5 months ago

This PR reduces allocations on StreamingHubClient hub method calls. It reduces allocations by 10-15%.

Breaking changes

Before

BenchmarkDotNet v0.13.12, Windows 11 (10.0.22631.3737/23H2/2023Update/SunValley3)
13th Gen Intel Core i7-13700KF, 1 CPU, 24 logical and 16 physical cores
.NET SDK 8.0.300
  [Host]   : .NET 8.0.5 (8.0.524.21615), X64 RyuJIT AVX2
  ShortRun : .NET 8.0.5 (8.0.524.21615), X64 RyuJIT AVX2

Job=ShortRun  IterationCount=3  LaunchCount=1
WarmupCount=3

| Method                            | Mean       | Error       | StdDev    | Rank | Gen0   | Gen1   | Allocated |
|---------------------------------- |-----------:|------------:|----------:|-----:|-------:|-------:|----------:|
| Void_Parameter_Zero_NoReturn      |   214.8 ns |    72.04 ns |   3.95 ns |    1 | 0.0052 | 0.0048 |      88 B |
| ValueTask_Parameter_Zero_NoReturn | 2,926.8 ns | 1,832.13 ns | 100.43 ns |    4 | 0.0458 |      - |     728 B |
| Parameter_Zero_Return_ValueType   | 3,001.6 ns | 1,587.29 ns |  87.00 ns |    5 | 0.0458 |      - |     720 B |
| Parameter_Many_Return_ValueType   | 2,793.2 ns | 1,250.25 ns |  68.53 ns |    2 | 0.0458 |      - |     746 B |
| Parameter_Zero_Return_RefType     | 2,895.2 ns | 1,184.97 ns |  64.95 ns |    3 | 0.0458 |      - |     760 B |
| Parameter_Many_Return_RefType     | 2,934.9 ns | 1,584.81 ns |  86.87 ns |    4 | 0.0458 |      - |     784 B |

After

BenchmarkDotNet v0.13.12, Windows 11 (10.0.22631.3737/23H2/2023Update/SunValley3)
13th Gen Intel Core i7-13700KF, 1 CPU, 24 logical and 16 physical cores
.NET SDK 8.0.300
  [Host]   : .NET 8.0.5 (8.0.524.21615), X64 RyuJIT AVX2
  ShortRun : .NET 8.0.5 (8.0.524.21615), X64 RyuJIT AVX2

Job=ShortRun  IterationCount=3  LaunchCount=1
WarmupCount=3

| Method                            | Mean       | Error     | StdDev   | Rank | Gen0   | Gen1   | Allocated |
|---------------------------------- |-----------:|----------:|---------:|-----:|-------:|-------:|----------:|
| Void_Parameter_Zero_NoReturn      |   243.1 ns |  56.32 ns |  3.09 ns |    1 | 0.0052 | 0.0048 |      88 B |
| ValueTask_Parameter_Zero_NoReturn | 2,928.9 ns | 589.08 ns | 32.29 ns |    4 | 0.0305 |      - |     584 B |
| Parameter_Zero_Return_ValueType   | 3,032.6 ns | 765.85 ns | 41.98 ns |    6 | 0.0305 |      - |     576 B |
| Parameter_Many_Return_ValueType   | 2,598.1 ns | 168.51 ns |  9.24 ns |    2 | 0.0343 |      - |     593 B |
| Parameter_Zero_Return_RefType     | 2,826.1 ns | 435.23 ns | 23.86 ns |    3 | 0.0381 |      - |     616 B |
| Parameter_Many_Return_RefType     | 2,973.4 ns | 860.79 ns | 47.18 ns |    5 | 0.0305 |      - |     632 B |