NetWasm README

README проекта с github.com/zion-sati/NetWasm. Одним файлом markdown: README.md.

NetWasm

Independent .NET for WebAssembly and WASI.
Write C#. Deploy small, standalone Wasm.

NetWasm is an independent compiler, CoreLib, runtime and SDK that compiles C# and .NET CIL directly to WebAssembly. It does not carry the desktop CLR, Mono, dotnet.js or application DLLs into production.

Star NetWasm on GitHub Publication Compiler coverage License: Community + MIT

Compile C# to WebAssembly · Try it in the browser · Install and build · See supported APIs · Read the documentation

C# at less than half Rust's Wasm size

NetWasm + precise GC: 28,377 bytes
Rust 1.100.0 size-oriented profile: 63,528 bytes

For the same print-42 workload, NetWasm's result includes the runtime and precise Compact garbage collector. Both artifacts are standalone WASI 0.3 components, built the way a developer gets them out of the box: each toolchain's standard library and ordinary build, with no hand-added tools.

55.3% smaller raw. 39.1% smaller with Brotli-11.

Wasm footprint landscape with raw and Brotli-11 sizes. NetWasm with precise GC is 28,377 raw and 11,880 compressed bytes; Rust is 63,528 and 19,519; Rust's WASI 0.2 build, shown for context, is 53,382 and 16,725; Kotlin/Wasm is 79,293 and 22,655; TinyGo is 93,043 and 26,931. NetWasm and Rust are the matched WASI 0.3 comparison; Kotlin and TinyGo are contextual Preview 1 references.

Toolchain Raw Wasm Brotli 11 Comparison role
NetWasm, Compact GC 28,377 B 11,880 B WASI 0.3 component; precise GC included
Rust 1.100.0, size profile 63,528 B 19,519 B Matched WASI 0.3 component reference
Rust 1.100.0, size profile 53,382 B 16,725 B WASI 0.2 component, for context
Kotlin 2.4.0 wasmWasi 79,293 B 22,655 B P1 context; GC supplied by the host engine
TinyGo 0.39.0 93,043 B 26,931 B P1 context; precise GC configured

Rust is the headline comparison because it uses the same workload and output form. Rust's WASI 0.2 build, Kotlin/Wasm and TinyGo show the broader footprint landscape, but their targets and runtime boundaries differ. This is a measured workload/profile result, not a language-wide size ranking.

NetWasm's figure is the template application's default Release publish. Rust's adds Cargo's documented size settings (opt-level = "z", LTO, one codegen unit, panic = "abort" and stripped symbols) to an ordinary cargo build. Binaryen's wasm-opt is not a post-processing step here: it is part of NetWasm's compiler pipeline and runs in every ordinary build, with nothing to install or enable. Rust's output is a component, so applying wasm-opt to it means extracting the core module, optimizing it and re-encoding the component by hand. For Rust 1.100.0's WASI 0.3 target that route does not yet produce a component that runs. For its WASI 0.2 target it does: with every custom section stripped as well, the component is 41,185 bytes (14,523 with Brotli-11), still larger than NetWasm's ordinary publish.

Both languages can go lower, but that is a different class of program: Rust with no_std, or C# with a minimal library such as bflat's zero library, each giving up most of the standard library and, for C#, the garbage collector.

Exact sources, versions, settings and reproduction steps

Faster than Mono AOT and the desktop JIT

NetWasm runs our allocation and garbage-collection benchmarks faster than Mono AOT, compiled from the same C# source and run by the same Wasmtime. It is also faster than desktop .NET 11's JIT and NativeAOT on all three, although desktop .NET runs native code outside any Wasm sandbox:

Workload NetWasm, NetWasmGC Mono AOT, .NET 11 Desktop .NET 11 JIT Desktop .NET 11 NativeAOT
Full transaction 26.7 ms 56.7 ms 50.5 ms 33.2 ms
Retained object graph 4.0 ms 14.2 ms 10.1 ms 7.9 ms
UI churn 5.4 ms 26.8 ms 9.0 ms 7.0 ms

These are medians of 15 runs on an Apple M1 Max, with every Wasm build under Wasmtime 50.0.1 and each run checked against desktop .NET's result. Mono AOT is Microsoft's wasi-wasm target on .NET 11 in Release, with Wasm SIMD. NetWasmGC takes 53% to 80% less time than Mono AOT, 40% to 60% less than the desktop JIT and 20% to 50% less than desktop NativeAOT.

Without allocation in the timed region, NetWasm takes 41% less time than Mono AOT on the transaction's library work, 10% less on a quicksort and 2% less on n-body and CRC-32 kernels. Desktop .NET is faster on the library work and the quicksort without allocation.

Versions, settings, desktop figures and reproduction

More than Hello World

Hello World is just the smallest example. NetWasm builds real applications too.

C# 15 · JavaScript modules and Web Workers · static .a interop · WIT/WASI 0.3 · expression trees · HTTP/JSON/XML/Regex · reflection-free DI · TUnit/VSTest · wasm64 · three allocation strategies

Today NetWasm can:

The profile is deliberately smaller than desktop .NET. It already supports complete applications, portable libraries, test projects and browser modules.

Built with NetWasm:

Try it

Install .NET SDK 10.0.303 or newer, then run:

dotnet new install NetWasm.Templates
dotnet new netwasm-app -n HelloNetWasm
cd HelloNetWasm
dotnet restore
dotnet run
dotnet publish -c Release -o publish/local

Run the published folder with Node.js, or the component with a WASI 0.3 host such as Wasmtime:

node publish/local/netwasm.host.mjs
wasmtime run -Wcomponent-model-async -Sp3 publish/local/HelloNetWasm.wasm
42

The published component is self-contained with respect to .NET. A WebAssembly host is still required. Build with .NET; run without .NET.

Projects using C# 15 select the .NET 11 SDK; earlier language versions can stay on .NET 10. The SDK restores its pinned Node, LLD and Binaryen tools through NuGet, so an ordinary app does not require a separate Emscripten, Git or Python installation. See the complete quickstart for host, restore, Windows, browser and dual-targeting details.

How it stays small

Roslyn produces CIL. NetWasm compiles the reachable program directly to Wasm, specializes its generics and links only the runtime support it needs. The linked Wasm component is the program.

This is a new .NET platform, not desktop .NET squeezed into a Wasm sandbox. That boundary is what makes native-Wasm-sized C# possible.

How JSON and optional features affect size

Choose your allocation strategy

Compact is the default: a size-first, precise, non-moving mark-and-sweep collector. It traces compiler-published roots and reference layouts without conservative scanning. Its name refers to implementation size, not moving heap compaction.

Strategy Best fit Raw component Brotli 11
Compact (default) Small applications and low-churn UI 28,377 B 11,880 B
NetWasmGC Higher allocation throughput 32,154 B 13,465 B
Bump Bounded, one-shot jobs 23,805 B 9,880 B

Select a strategy in the executable project's .csproj:

<PropertyGroup>
  <NetWasmGarbageCollector>NetWasm</NetWasmGarbageCollector>
</PropertyGroup>

Leaving the property unset selects Compact. Libraries remain collector-neutral; all four backends are packaged for wasm32 and wasm64. See Choosing a garbage collector for the tradeoffs and diagnostics.

Libraries should travel upward

A library written for the smaller NetWasm profile should also be useful on desktop .NET, rather than trapped in a Wasm-only ecosystem.

dotnet new netwasm-lib -n MyLibrary

The template targets netwasm0.1 and net10.0, producing NuGet assets for both platforms. This is explicit multi-targeting, not a promise that arbitrary desktop packages work in reverse.

NetWasm.Libraries provides the ported framework and extensions packages. TUnit-NetWasm provides ordinary dotnet test integration through the generic VSTest bridge.

How does this compare to conventional .NET Wasm?

For an empty-UI Blazor WebAssembly application that prints 42, with AOT, managed trimming, IL stripping, invariant globalization and size-focused native linking enabled:

AOT Wasm size comparison, lower is better: NetWasm with Compact GC 27.7 KiB, Blazor .NET 10 11.71 MiB, Blazor .NET 11 RC1 14.58 MiB. NetWasm is about 539 times smaller than the .NET 11 build by exact bytes.

AOT build Uncompressed Wasm Relative to NetWasm
NetWasm, Compact GC 28,377 B 1×
Blazor WebAssembly, .NET 10 12,276,684 B 433×
Blazor WebAssembly, .NET 11 RC1 15,289,241 B 539×

The Blazor total includes its native runtime and required Webcil assemblies; NetWasm includes its runtime, garbage collector and WASI component. This is a console component versus an empty-UI application, not an equivalent-framework comparison or a claim about every .NET workload.

Exact Blazor versions, settings and reproduction

Current boundary

NetWasm is pre-1.0. Its supported profile is usable today and covered by published qualification, but source, package, target-profile and ABI contracts may change between minor releases.

The normal portable output is a wasm32 WASI 0.3 Component. Raw wasm32, raw wasm64 and JavaScript-host integration are advanced alternatives; wasm64 Components remain blocked by upstream tooling.

Runtime reflection, dynamic, runtime assembly loading and managed threading are outside the profile. General System.IO.File/Directory/FileStream, raw sockets and subprocess APIs are not yet implemented. Existing NuGet packages work only when their reachable code and API dependencies fit the supported profile.

Supported APIs and limitations · Documentation index

Road to 1.0

NetWasm 1.0 means a useful, documented and stable smaller platform. It does not mean “desktop .NET, but in Wasm.” The main themes are:

New in NetWasm 0.13.0: programs no longer carry type names, which read type#<id> unless a file beside the program supplies them; calls through unmanaged function pointers; async programs about half the size and the program that prints 42 23% smaller; and console output that JavaScript hosts no longer lose. Release notes. NetWasm 0.12.2 lets dotnet run and NetWasm's other Node.js hosts run programs that use sockets, and a call into a program costs the same however much it keeps alive: calls no longer collect garbage on their own, and finalizers, weak references, GC handles and pending asynchronous work are tracked in constant time. Release notes. NetWasm 0.12.1 ends a program with the exit code desktop .NET gives it, and adds Environment.Exit, Environment.ExitCode and Environment.FailFast. Release notes. NetWasm 0.12.0 made components target WASI 0.3, so ordinary .NET file, socket and HttpClient code runs on the Component Model, and an HTTP service is one Handle method that Wasmtime, Spin and wasmCloud run unchanged. NetWasmGC allocates small objects inline, so a binary-trees benchmark takes 28% less time at O3. Release notes. NetWasm 0.11.3 let static native libraries use Wasm SIMD. Release notes. NetWasm 0.11.2 brought faster delegate calls and span loops, and a compiler that needs half the memory: a delegate call takes 38% less time, a multicast invoke 44% less, and a fold over a span runs as Wasm SIMD vectors. Compiling DoomSharp's browser build at O3 peaks at 1.5 GB where 0.11.1 took 3.4 GB. Release notes. NetWasm 0.11.0 made Debug builds keep each method's compiled code, so a rebuild compiles only what an edit changes: on DoomSharp's browser build, an edit to one method rebuilds in 1.6 s where 0.10.8 took 29.3 s, and dotnet watch runs on NetWasm projects. Release notes

In progress: broader compatibility with existing .NET Standard 2.1 library binaries and NuGet assets. The target is to consume libraries unchanged when their reachable code fits the NetWasm profile, without carrying unused unsupported paths into the application.

This does not turn NetWasm into desktop .NET. Reachable general runtime reflection, dynamic, runtime assembly loading, managed threading, unsupported host APIs and named-culture globalization remain outside the initial compatibility slice and fail at compile time.

Read the full 1.0 roadmap

Packages

Compiler, SDK, runtime and hosting packages

NetWasm.Compiler.Browser · NetWasm.Compiler.Tasks · NetWasm.Hosting · NetWasm.Hosting.Build · NetWasm.Ref · NetWasm.Runtime.Pack · NetWasm.Runtime.Wasm32 · NetWasm.Runtime.Wasm64 · NetWasm.Sdk · NetWasm.Templates · NetWasm.Testing.VSTest · NetWasm.Toolchain · NetWasm.Wit.Bindings.Tool

Ported-library packages · TUnit packages

License

CoreLib, runtime libraries, templates and generated support code are MIT, subject to preserved upstream notices. The compiler and developer tooling use the NetWasm Community License 1.0. The Compact and NetWasmGC collectors are Apache-2.0.

The Community License is free for individuals, education, open-source projects, evaluation, and small and medium-sized businesses: any organization with fewer than 250 employees and less than USD 10,000,000 in annual revenue. Larger organizations pay for internal commercial use by sponsoring a matching GitHub Sponsors tier, from USD 149 a month for five developers up to USD 2,499 a month for unlimited developers. OEM and Commercial Offering use require a separate agreement. Generated applications may use their authors' chosen licenses. The sponsorship itself is the license: there is no license key, sign-in, activation, telemetry or technical enforcement.

Licensing guide · Third-party notices · Commercial licensing: [email protected]

Bring a workload

Start with Console.WriteLine(42), then try the smallest real workload where deployment size, sandboxing or portability matters. If something is missing, open an issue. Concrete workloads are how the 1.0 support boundary gets decided.

NetWasm (zion-sati/NetWasm)

Ищем в базе…

Что это такое?NetWasm — это независимый компилятор, CoreLib, среда выполнения и SDK, которые компилируют C# и .NET CIL напрямую в небольшой автономный WebAssembly с WASI, не перенося в продакшен настольный CLR, Mono, dotnet.js или DLL приложения.
Это полноценная среда выполнения .NET для Wasm или отдельная, более компактная платформа?Это новая, отдельная платформа, похожая на .NET, созданная специально для Wasm, а не настольный .NET, втиснутый в песочницу Wasm; у неё собственные компилятор с замкнутым миром, CoreLib и среда выполнения.
Как собрать и запустить проект NetWasm?Установите .NET SDK 10.0.303 или новее и соберите проект обычной командой dotnet CLI, затем запустите опубликованный компонент WASI Preview 2 с совместимым хостом, например Wasmtime.
Нужно ли отдельно ставить Emscripten, Git или Python?Нет, SDK сам загружает через NuGet закреплённые версии Node, LLD и Binaryen, поэтому обычному приложению не нужна отдельная установка Emscripten, Git или Python.
Какие возможности .NET пока недоступны?Пока не поддерживаются общая рефлексия времени выполнения, ключевое слово dynamic, загрузка сборок во время выполнения, управляемые потоки, а также общие API System.IO.File, Directory и FileStream, сырые сокеты и подпроцессы; пакеты NuGet работают только в том случае, если достижимый код укладывается в поддерживаемый профиль.
Насколько NetWasm компактнее Rust или Blazor?Для одной и той же задачи print-42 компонент NetWasm WASI P2 с точным сборщиком мусора занимает 47 798 байт, что примерно на 10,9% меньше сырого размера сборки Rust с оптимизацией по размеру (53 635 байт), и примерно в 257 раз меньше эквивалентного приложения Blazor WebAssembly с пустым интерфейсом (12,27 МБ).
Какой сборщик мусора выбрать?Compact — это используемый по умолчанию точный сборщик, ориентированный на размер, для небольших приложений и интерфейсов с редкими выделениями памяти; NetWasmGC обеспечивает более высокую пропускную способность выделения памяти, Bump подходит для ограниченных одноразовых задач, а Boehm даёт совместимость с консервативным сборщиком. Выбирается он свойством в .csproj.
Можно ли писать библиотеки, которые работают и в Wasm, и в настольном .NET?Да: шаблон проекта создаёт сборку сразу для netwasm0.1 и net10.0, чтобы пакеты NuGet содержали ресурсы для обеих платформ, а NetWasm.Libraries предоставляет портированные пакеты фреймворка для этой цели.
Готов ли NetWasm к промышленному использованию?Пока это версия до 1.0: поддерживаемый профиль уже можно использовать, но контракты на исходный код, пакеты, целевой профиль и ABI могут меняться между минорными выпусками, а расширенная поддержка System.IO и локализации запланирована на 0.9.0 и 1.0.
Какие есть похожие проекты?wasmtime, sentry-dotnet, wasmer, AstraFlow, uno, Polly, roslyn, Newtonsoft.Json
В каких он темах?aot, dependency-injection, webassembly, dotnet, compiler, c#, csharp, http, wasm, json, testing, sdk
Автор
zion-sati
Размер
39.5 MB
Звёзды
361
Возраст
3 мес
Коммиты · 90 дней