當前位置: 妍妍網 > 碼農

一個C#開發的大小只有8KB的貪吃蛇開源遊戲!

2024-02-21碼農

大家好,我是編程樂趣。

今天給大家推薦基於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,還能進一步最佳化!大家感興趣的可以自行嘗試下。

- End -

分享一套.NetCore從入門到精通視訊教程

點選下方公眾號卡片,關註我

回復「 888 」,免費領取

推薦閱讀

覺得好看 點個在看👇