當前位置: 妍妍網 > 碼農

C# 開源遊戲 只有8KB的貪吃蛇

2024-02-26碼農

前言

給大家推薦基於C#開發的、一個貪吃蛇開源計畫,這個計畫除了實作貪吃蛇的功能外,重點是講解如何把編譯後的程式,從65MB精簡為8KB。

計畫地址

https://github.com/MichalStrehovsky/SeeSharpSnake

正文

編譯精簡過程如下:

1、正常釋出,大小為65MB

dotnet publish -r win-x64 -c Release

2、添加參數/p:PublishTrimmed=true,移除未使用的程式碼,大小為25MB

dotnet publish -r win-x64 -c Release /p:PublishTrimmed=true

3、使用CoreRT的編譯模式,大小為4.7MB

dotnet publish -r win-x64 -c Release /p:Mode=CoreRT

4、使用CoreRT-Moderate的編譯模式,大小為4.3MB

dotnet publish -r win-x64 -c Release /p:Mode=CoreRT-Moderate

5、使用CoreRT-High的編譯模式,大小為3.0MB

dotnet publish -r win-x64 -c Release /p:Mode=CoreRT-High

6、使用CoreRT-ReflectionFree的編譯模式,大小為1.2MB

dotnet publish -r win-x64 -c Release /p:Mode=CoreRT-ReflectionFree

7、使用CoreRT-NoRuntime的編譯模式,大小為10KB

dotnet publish -r win-x64 -c Release /p:Mode=CoreRT-NoRuntime

8、采用csc.exe編譯,大小為8KB

//編譯C#程式碼
csc.exe /debug /O /noconfig /nostdlib /runtimemetadataversion:v4.0.30319 MiniRuntime.cs MiniBCL.cs Game\FrameBuffer.cs Game\Random.cs Game\Game.cs Game\Snake.cs Pal\Thread.Windows.cs Pal\Environment.Windows.cs Pal\Console.Windows.cs Pal\Console.cs /out:zerosnake.ilexe /langversion:latest /unsafe
//將庫組合成一個可執行檔
link.exe /debug:full /subsystem:console zerosnake.obj /entry:__managed__Main kernel32.lib ucrt.lib /merge:.modules=.rdata /merge:.pdata=.rdata /incremental:no /DYNAMICBASE:NO /filealign:16 /align:16

以上就是作者嘗試的編譯精簡過程,我們使用比較多是第2步,其他步驟可能會有相容問題,實際計畫要慎用。

但是.NET 7開始支持AOT,還能進一步最佳化!大家感興趣的可以自行嘗試下。

- EOF -

推薦閱讀 點選標題可跳轉

看完本文有收獲?請轉發分享給更多人

推薦關註「DotNet」,提升.Net技能

點贊和在看就是最大的支持❤️