1. 程式人生 > >是什麼優化讓 .NET Core 效能飆升?

是什麼優化讓 .NET Core 效能飆升?

using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
class Test
{
    static void Main()
    {
        using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task connectTask = Task.Run(() => client.Connect(listener.LocalEndPoint));
using (Socket server = listener.Accept()) { connectTask.Wait(); using (var clientAre = new AutoResetEvent(false)) using (var clientSaea = new SocketAsyncEventArgs()) using (var serverAre = new AutoResetEvent(false))
using (var serverSaea = new SocketAsyncEventArgs()) { byte[] sendBuffer = new byte[1000]; clientSaea.SetBuffer(sendBuffer, 0, sendBuffer.Length); clientSaea.Completed += delegate { clientAre.Set(); }; byte[] receiveBuffer = new byte[1000]; serverSaea.SetBuffer(receiveBuffer, 0, receiveBuffer.Length); serverSaea.Completed += delegate { serverAre.Set(); }; var sw = new Stopwatch(); int gen0 = GC.CollectionCount(0), gen1 = GC.CollectionCount(1), gen2 = GC.CollectionCount(2); sw.Start(); for (int i = 0; i < 1_000_000; i++) { if (client.SendAsync(clientSaea)) clientAre.WaitOne(); if (clientSaea.SocketError != SocketError.Success) throw new SocketException((int)clientSaea.SocketError); if (server.ReceiveAsync(serverSaea)) serverAre.WaitOne(); if (serverSaea.SocketError != SocketError.Success) throw new SocketException((int)clientSaea.SocketError); } Console.WriteLine($"Elapsed={sw.Elapsed} Gen0={GC.CollectionCount(0) - gen0} Gen1={GC.CollectionCount(1) - gen1} Gen2={GC.CollectionCount(2) - gen2}"); } } } } }