NetWasm 0.10: Optimising C# Ahead-of-Time WebAssembly

NetWasm 0.10 introduces SIMD lowering, division reuse, and frame management optimisations, outperforming Mono AOT across benchmark suites.

TL;DR

  • What happened: The NetWasm project released its 0.10 optimisation series (spanning versions 0.10.1 through 0.10.8), transforming C# intermediate language (IL) directly into standalone WebAssembly without relying on full Mono execution wrappers.
  • Who is affected: Platform engineers, software architects, and systems developers building high-performance C# services or front-end applications for WebAssembly System Interface (WASI) engines and web browsers.
  • Performance impact: Across 2,213 test cases from dotnet/performance, NetWasm 0.10.8 at O3 with NetWasmGC achieves a geometric mean execution time ratio of 0.41 relative to Mono AOT and 0.87 relative to desktop .NET 11 RC3 JIT.
  • Key bottlenecks & regressions: Desktop .NET remains 3.1 times faster on vector workloads due to host 256/512-bit SIMD hardware. Math.Pow is 1.4 times slower than Mono AOT, CopyBlock64 is 3.3 times slower, and the NewtR benchmark regressed 1.9 times slower due to Wasmtime register spilling.
  • What to do now: Evaluate NetWasm 0.10.8 for CPU-bound C# WASI workloads, profile vector code for 128-bit WebAssembly SIMD boundaries, and enforce 4 KiB function alignment when conducting local performance diagnostics.

According to technical details reported by InfoQ, the open-source netwasm 0.10 release series introduces structural compiler optimisations that allow ahead-of-time (AOT) compiled C# code to outperform traditional Mono AOT builds on WebAssembly. Spanning releases 0.10.1 to 0.10.8 published in late 2026, the engine targets critical runtime overheads: frame preservation during exception handling, redundant array bounds validation, 128-bit vector lowering, and integer division reuse.

Historically, deploying C# applications to WebAssembly System Interface (WASI) environments meant executing within the Mono AOT runtime framework. While functional, Mono’s compilation strategy retains legacy execution frame structures and runtime checks that introduce measurable latency during intensive loop processing. NetWasm alters this model by ingesting intermediate language (IL) bytecode generated by Microsoft’s Roslyn compiler and emitting standalone WebAssembly modules directly, supported by a custom ported CoreLib runtime and a dedicated garbage collector designated as NetWasmGC.

In comparative evaluation using Wasmtime 49.0.3 on an Apple M1 Max host across 2,213 benchmark cases from the official dotnet/performance repository along with five custom NetWasm workloads, NetWasm 0.10.8 achieved a geometric mean execution time ratio of 0.41 relative to Mono AOT. This optimisation effort also narrowed the performance gap with host execution: NetWasm’s execution time ratio relative to desktop .NET 11 RC3 JIT dropped from 2.15 in version 0.10.6 down to 0.87 in version 0.10.8.

Rethinking C# Execution on WebAssembly Beyond Mono AOT

For several years, targetting WebAssembly from the .NET ecosystem required routing execution through the Mono runtime. In a standard Mono AOT build for WASI, the compiler converts C# IL into native WebAssembly instructions or LLVM Intermediate Representation (IR). However, the resulting module must still interface with Mono’s internal execution engine to handle object allocations, type checking, method dispatching, and stack unwinding. While this design maintains absolute feature parity with standard .NET runtimes, it introduces structural overhead for computationally dense algorithms.

NetWasm eliminates this runtime layer by treating WebAssembly as a primary target architecture rather than an emulation layer. The compiler ingests standard Roslyn-generated IL bytecode and maps it directly into WebAssembly binary opcodes. Memory management, runtime allocation, and type metadata are handled by a lightweight ported CoreLib and NetWasmGC, removing standard interpreter frames and indirect call tables.

+-----------------------------------------------------------------------+
|                         C# Source Code (.cs)                          |
+-----------------------------------------------------------------------+
                                    |
                                    v (Roslyn Compiler)
+-----------------------------------------------------------------------+
|                       .NET Intermediate Language                      |
+-----------------------------------------------------------------------+
                                    |
            +-----------------------+-----------------------+
            |                                               |
            v (Standard WASI Path)                          v (NetWasm 0.10 Path)
+---------------------------------------+       +-------------------------------+
|           Mono AOT Engine             |       |    NetWasm Direct AOT Pass    |
| - LLVM / Interpreter Wrappers         |       | - Direct Roslyn IL Lowering   |
| - Dynamic Metadata Lookups            |       | - NetWasmGC Runtime           |
| - Heavy Frame Preservation            |       | - Direct Wasm Vector Opcode   |
+---------------------------------------+       +-------------------------------+
            |                                               |
            v                                               v
+-----------------------------------------------------------------------+
|                 Standalone WebAssembly Module (.wasm)                 |
+-----------------------------------------------------------------------+
                                    |
                                    v
+-----------------------------------------------------------------------+
|                    Wasmtime Runtime (Host Engine)                     |
+-----------------------------------------------------------------------+

Prior to the 0.10 release series, NetWasm’s dedicated garbage collector had already provided performance advantages in allocation-heavy code paths. However, tight, unrolled numeric loops lagged behind competing runtimes. For example, sorting an array of 100,000 integers via quicksort required 77.2 ms in NetWasm 0.10.1, whereas Mono AOT completed the identical workload in 58.0 ms. The 0.10 optimisation series targeted these precise loop inefficiencies through systematic compiler refactoring.

Workload / Benchmark Mono AOT (ms) NetWasm 0.10.1/0.10.6 (ms) NetWasm 0.10.8 (ms) Desktop .NET 11 RC3 (ms)
Quicksort (100,000 integers) 58.0 77.2 (v0.10.1) 54.0 (v0.10.2) Not reported
DoomSharp Software Render (120 frames) 2,371.0 3,595.0 (v0.10.1) 1,623.0 (NetWasmGC) 1,053.0
Burgers’ Equation PDE Solver 186.0 497.0 (v0.10.6) 71.0 (v0.10.7) 93.0
Trial-Division Prime Algorithm 862.0 1,376.0 (v0.10.6) 765.0 (v0.10.8) Not reported

Architectural Pipeline: From Roslyn IL to Standalone Wasm Bytecode

The NetWasm compilation pipeline bypasses native LLVM IR intermediate steps, translating C# assembly manifests directly into WebAssembly module structures. When Roslyn compiles C# source code, it outputs stack-based IL instructions such as ldarg, ldloc, add, and stelem. NetWasm ingests these constructs and constructs an internal control flow graph (CFG) designed to map stack operations directly onto WebAssembly’s native stack machine architecture.

During compilation, NetWasm analyses type definitions and replaces generic framework dependencies with its custom, minimal CoreLib runtime. Object instances are allocated within linear memory managed by NetWasmGC, avoiding the overhead of external runtime hosting. Because WebAssembly modules are completely self-contained, methods can be aggressively inlined across assembly boundaries without incurring dynamic symbol lookup penalties.

A critical technical challenge in validating AOT execution performance on host engines like Wasmtime is instruction address layout variance. During development of the 0.10 series, engineers identified that identical loop blocks could exhibit execution time variations of up to 15 percent depending entirely on their code address offsets within the compiled binary module. Microarchitectural features on host CPUs—such as instruction cache line boundaries and branch target buffers (BTB)—react differently when functions shift positions in memory.

To eliminate address-dependent instruction alignment noise during performance evaluation, NetWasm implemented precise 4 KiB function alignment for A/B testing across all benchmarks. Enforcing 4 KiB boundaries ensures that every compiled WebAssembly function starts at a deterministic page offset, stabilizing host JIT emission inside Wasmtime’s Cranelift backend and providing predictable microbenchmarking data.

Eliminating Exception and Check Overhead in Wasmtime Frame Management

In WebAssembly runtimes such as Wasmtime, executing code that can throw managed exceptions requires non-trivial frame tracking overhead. When WebAssembly code contains explicit throw points or catch handlers, host engines must insert register save-and-restore instructions around function entry and exit points. Under Wasmtime 49.0.3, this frame preservation sequence saves both general-purpose and floating-point registers to host memory to maintain exact execution stack state in the event of an unwinding trap.

Impact of Implicit Exception Guards

In standard C# IL compilation, implicit exception safety checks—such as array index bounds checks, null pointer dereferences, and integer overflow checks—generate conditional throw paths inside routine functions. Consequently, every method executing an array access or object field read incurs Wasmtime register preservation overhead on every call frame.

NetWasm 0.10.1 restructured this exception architecture entirely. Rather than embedding distinct throw setup sequences and register save states across every checked method, the compiler refactored exception routes so that all throws pass through a centralized, shared helper function. When an exception occurs, frame releasing is deferred entirely to the catching handler using a dedicated unwind mechanism, allowing calling methods to omit local register save-and-restore operations.

// Conceptual IL representation of array access safety checks
// BEFORE NetWasm 0.10.1 (Per-method throw emission and frame context saving):
public int ReadElement(int[] data, int index)
{
    if (data == null) 
        throw new ArgumentNullException(nameof(data)); // Forces Wasmtime register save
    if ((uint)index >= (uint)data.Length) 
        throw new IndexOutOfRangeException();          // Forces Wasmtime register save
        
    return data[index];
}

// AFTER NetWasm 0.10.1 (Shared throw routing and handler-based frame releasing):
public int ReadElementOptimised(int[] data, int index)
{
    // Fast path eliminates register save blocks; calls shared throw stub on failure
    if (data != null && (uint)index < (uint)data.Length)
    {
        return data[index];
    }
    
    return NetWasmRuntime.RaiseBoundsExceptionShared(data, index);
}

By delegating frame preservation to a shared exception route, normal execution paths retain minimal register state. In benchmark workloads measuring UI event handling and frame updates, this structural change reduced UI frame churn from 17.6 ms per operation down to 7.9 ms, representing a 55 percent reduction in rendering latency.

Inlining, Value Types, and Redundant Check Elimination in Loop Hotspots

Building on the exception refactoring of version 0.10.1, NetWasm 0.10.2 focused on loop optimisation passes. The compiler introduced aggressive straight-line method inlining, identifying small functions without complex control flow—such as tuple swap operations and mathematical helper functions—and expanding their bytecode directly into the calling basic block.

Simultaneously, the compiler implemented redundant array bounds and index check elimination. In managed runtimes, array indexing operations typically emit safety traps to guarantee memory safety. However, inside tight loops where an array’s length and loop index variables are guarded by an outer condition, subsequent array reads within the same basic block are guaranteed to be safe. NetWasm’s optimization pass analyses dominance trees in the control flow graph to strip out duplicate bounds verification code.

# Standard CLI command to compile C# applications using NetWasm O3 optimization level
netwasm compile --configuration Release --opt-level O3 \
  --enable-bounds-elimination \
  --enable-struct-flattening \
  --output ./build/app_optimised.wasm ./src/App.csproj

Another optimization introduced in 0.10.2 targets value types (`struct`). Historically, accessing properties on C# value types generated temporary copy allocations on the evaluation stack and invoked property accessor methods. NetWasm 0.10.2 flattens value-type accessors directly into plain memory field loads (`i32.load` and `f64.load`). At the `O3` optimization tier, small conditional branching helpers within hot loops are inlined, transforming indirect memory access into contiguous, linear operations.

These loop optimizations produced immediate performance gains:

  • Quicksort Benchmark: Execution time for sorting a 100,000-integer array dropped from 77.2 ms down to 54.0 ms, successfully outperforming Mono AOT’s score of 58.0 ms.
  • DoomSharp Renderer: DoomSharp, a native C# software rendering engine for Classic Doom, served as a core real-world workload. Value-type accessor flattening and loop helper inlining reduced the rendering time for a 120-frame sequence from 3,595 ms down to 1,934 ms. In NetWasm 0.10.8 with NetWasmGC enabled, this score improved further to 1,623 ms (compared to 2,371 ms under Mono AOT and 1,053 ms on desktop .NET 11 RC3 JIT).

WebAssembly SIMD Lowering and Vectorised Arithmetic Performance

WebAssembly SIMD introduces fixed-width 128-bit vector operations (represented by the v128 value type) to the Wasm execution specification. Released in version 0.10.7, NetWasm’s vectorisation pass maps high-level C# SIMD APIs—specifically System.Runtime.Intrinsics.Vector128<T>, System.Numerics.Vector<T>, and PackedSimd—directly to native 128-bit WebAssembly instructions.

Vector Unrolling Mechanics

When compiling vectorised array iterations, NetWasm’s loop transformation engine processes contiguous memory in chunks of four or more elements per iteration using 128-bit WebAssembly instructions (`v128.load`, `i32x4.add`, `f32x4.mul`). Any remaining unaligned elements at array boundaries automatically fall back to a scalar cleanup loop.

In addition to instruction lowering, version 0.10.7 introduced loop-invariant math call hoisting. When mathematical routines (such as pure standard library calls) occur within a vectorised loop body with invariant arguments, the compiler extracts the call out of the loop header, eliminating redundant scalar recalculations per iteration.

// Scalar representation of fluid dynamics computational loop
public void ComputeBurgersEquation(float[] u, float[] uNext, float dt, float dx, int count)
{
    float nu = 0.07f; // Viscosity coefficient
    float c = dt / dx;
    float d = nu * dt / (dx * dx);

    // NetWasm 0.10.7 hoists invariant coefficients and vectorises the core body into v128 instructions
    for (int i = 1; i < count - 1; i += 4)
    {
        // Lowered directly to WebAssembly 128-bit vector loads and arithmetic opcodes
        var uVec = Vector128.LoadUnaligned(ref u[i]);
        var uLeft = Vector128.LoadUnaligned(ref u[i - 1]);
        var uRight = Vector128.LoadUnaligned(ref u[i + 1]);

        var term1 = Vector128.Multiply(uVec, Vector128.Create(c));
        var diff1 = Vector128.Subtract(uVec, uLeft);
        var spatial = Vector128.Subtract(Vector128.Add(uRight, uLeft), Vector128.Multiply(uVec, Vector128.Create(2.0f)));

        var result = Vector128.Subtract(Vector128.Subtract(uVec, Vector128.Multiply(term1, diff1)), Vector128.Multiply(Vector128.Create(d), spatial));
        result.StoreUnaligned(ref uNext[i]);
    }
}

The impact of vector lowering was measured using a numerical solver for Burgers’ equation—a non-linear partial differential equation fundamental to fluid mechanics modeling. In NetWasm 0.10.6 (prior to SIMD lowering), solving the PDE workload required 497 ms. In version 0.10.7, execution dropped to 71 ms. For comparison, Mono AOT completed the same workload in 186 ms, while desktop .NET 11 RC3 JIT required 93 ms on the same hardware host.

Division Reuse and Arithmetic Edge Case Optimisations in NetWasm 0.10.8

Version 0.10.8 targeted basic integer arithmetic operations, specifically division (`/`), remainder (`%`), and associated runtime safety boundaries. In C# source code, mathematical algorithms frequently perform paired division and remainder calculations on identical operands (for instance, `q = a / b; r = a % b;`). Standard compilation emits separate div_s (or div_u) and rem_s (or rem_u) WebAssembly instructions, with each instruction requiring independent zero-divisor check branches.

NetWasm 0.10.8 introduced an arithmetic unification pass. When the optimizer detects a remainder operation immediately following a division operation using identical inputs, it reuses the calculated quotient. The remainder is derived using a single multiply-subtract sequence (`r = a – (q * b)`), bypassing second hardware division instructions and completely omitting redundant zero-divisor validation checks.

Furthermore, the compiler eliminated duplicate checks for the int.MinValue / -1 arithmetic boundary condition. In WebAssembly, dividing -2147483648 by -1 triggers an integer overflow exception unless guarded. By validating overflow constraints once per basic block, NetWasm avoids issuing extra conditional checks on chained arithmetic operations.

// Microbenchmark pattern: Trial-division prime detection algorithm
public bool IsPrimeTrialDivision(ulong candidate)
{
    if (candidate < 2) return false;
    if (candidate % 2 == 0) return candidate == 2;
    
    ulong limit = (ulong)Math.Sqrt(candidate);
    for (ulong divisor = 3; divisor <= limit; divisor += 2)
    {
        // NetWasm 0.10.8 unifies division and remainder, eliminating duplicate zero-divisor guards
        ulong quotient = candidate / divisor;
        ulong remainder = candidate - (quotient * divisor);
        
        if (remainder == 0) return false;
    }
    return true;
}

In a trial-division prime factorisation benchmark, division unification reduced total execution time from 1,376 ms in version 0.10.6 down to 765 ms in version 0.10.8, outperforming Mono AOT’s recorded time of 862 ms.

Across the complete suite of 2,213 test cases, NetWasm 0.10.8 achieved an overall geometric mean execution time ratio of 0.41 relative to Mono AOT (excluding five benchmark cases where Mono’s LLVM backend completely eliminated dead-code loops). Categorical performance ratios relative to Mono AOT varied across domain types:

  • Hardware Intrinsics & SIMD: 0.34 geometric mean ratio relative to Mono AOT.
  • General Mathematical Routines: 0.81 geometric mean ratio relative to Mono AOT.
  • Overall Suite Ratio vs Desktop .NET: 0.87 geometric mean ratio relative to desktop .NET 11 RC3 JIT (down from 2.15 in version 0.10.6).

Benchmark Methodology, Remaining Bottlenecks, and Wasmtime Stack Allocations

Evaluating compiler performance requires an accurate understanding of runtime test conditions, hardware constraints, and workload regressions. All performance data reported for NetWasm 0.10 was measured on an Apple M1 Max host system executing Wasmtime 49.0.3. The evaluation dataset comprised 2,213 individual test cases selected from the official dotnet/performance repository, alongside five dedicated real-world workloads including DoomSharp and the Burgers’ equation solver.

Host Register Hardware Disparity

Despite NetWasm 0.10.8 achieving a 0.87 overall ratio against desktop .NET 11 RC3 JIT, desktop .NET remains approximately 3.1 times faster on raw vector benchmarks. Desktop runtimes utilize 256-bit (AVX-256) or 512-bit (AVX-512) host registers, whereas WebAssembly code is strictly bounded by the 128-bit Wasm SIMD spec.

While NetWasm 0.10 outperforms Mono AOT on the majority of evaluated test cases, specific algorithms demonstrate structural performance gaps and regressions:

  • Math.Pow Execution: NetWasm executes Math.Pow 1.4 times slower than Mono AOT. Mono links directly to highly optimized native C math library routines within its WASI runtime host, whereas NetWasm routes transcendental math through its managed CoreLib implementation.
  • CopyBlock64 Memory Transfers: Block memory copies executed via CopyBlock64 run 3.3 times slower than Mono AOT. Mono translates block operations directly to native host memcpy calls, whereas NetWasm emits unrolled linear memory byte stores that incur Wasm boundary overhead.
  • NewtR Benchmark Regression: In the NewtR benchmark workload, NetWasm 0.10.8 regressed to run 1.9 times slower than version 0.10.6. Architectural analysis identified the root cause inside Wasmtime’s Cranelift register allocation phase: changes to NetWasm’s intermediate loop lowering caused Cranelift to spill an active loop variable into a stack memory slot instead of retaining it in a host CPU register.

Engineers evaluating these benchmarks should note several unconfirmed environmental factors. Performance metrics across alternative WebAssembly runtimes—such as Google V8, Apple JavaScriptCore, WasmEdge, or Wasmer—have not been disclosed. Additionally, binary output file sizes and runtime memory consumption metrics relative to standard Mono WASI outputs have not been published. Multi-threading support (via WebAssembly threads) and targetting future 256-bit SIMD proposals also remain outside the current release scope.

Practical Adoption Strategy and Technical Takeaways for Engineers

Platform engineers considering NetWasm 0.10 for WebAssembly workloads should adopt a targeted diagnostic evaluation strategy before migrating existing Mono AOT pipelines.

When to Select NetWasm 0.10 over Mono AOT

  • CPU-Intensive Algorithm Engine: Workloads dominated by array sorting, numerical fluid solvers, image processing, or software graphics rendering benefit significantly from NetWasm’s direct IL lowering and bounds elimination.
  • Allocation-Heavy Execution: Applications with high object turnover profit from NetWasmGC, which avoids Mono’s generic object frame wrappers.
  • Standard WASI Microservices: Standalone CLI utility binaries targetting Wasmtime or Enarx environments achieve faster execution ratios.

Common Implementation Mistakes

Common Pitfalls in WebAssembly C# Optimisation

  • Assuming Desktop SIMD Parity: Translating 256-bit broad vector algorithms directly to C# SIMD without accounting for WebAssembly’s 128-bit limit can lead to unexpected host register spilling.
  • Relying on Host Math Wrappers: Assuming mathematical functions like Math.Pow will match native C speed; high-frequency transcendental operations should be benchmarked carefully.
  • Ignoring Register Spilling in Custom Loops: Failing to test compiled Wasm binaries under Wasmtime’s verbose JIT disassembly, missing stack slot spills similar to the NewtR regression.

Diagnostics and Profiling Workflow

To verify performance locally, engineers should clone the official repository, compile binaries using the release toolchain, and execute benchmarks under controlled alignment flags:

# Step 1: Install the NetWasm 0.10 toolchain and CLI driver
dotnet tool install --global NetWasm.CLI --version 0.10.8

# Step 2: Compile target assembly with explicit function alignment for deterministic testing
netwasm publish ./src/ComputeEngine.csproj \
  -c Release \
  --opt-level O3 \
  --align-functions 4096 \
  -o ./wasm_dist

# Step 3: Profile execution under Wasmtime 49.0.3 with Cranelift debug logging enabled
wasmtime run --wasi-modules=experimental-wasi \
  --c-header \
  ./wasm_dist/ComputeEngine.wasm

By understanding the precise trade-offs between 128-bit SIMD limits, frame preservation mechanics, and host register allocation, platform teams can effectively leverage NetWasm 0.10 to build high-performance WebAssembly systems in C#.

Frequently asked questions

How does NetWasm 0.10 achieve faster execution than Mono AOT on WebAssembly?

NetWasm 0.10 bypasses the traditional Mono runtime wrapper by lowering Roslyn-generated IL directly into standalone WebAssembly opcodes. Combined with its custom NetWasmGC, version 0.10 refactors exception routes to eliminate Wasmtime register save overhead, removes redundant array bounds checks in hot loops, and lowers SIMD operations directly to 128-bit Wasm vector primitives.

Why does desktop .NET still outperform NetWasm on vector-heavy operations?

Desktop .NET 11 JIT executes directly on host hardware capable of leveraging 256-bit (AVX-256) or 512-bit (AVX-512) vector instruction registers. In contrast, NetWasm is constrained by the current WebAssembly SIMD specification, which limits vector operations to 128-bit width. This hardware register width disparity allows desktop .NET to run vector benchmarks approximately 3.1 times faster.

What caused the performance regression in the NewtR benchmark under NetWasm 0.10.8?

The 1.9x performance regression in the NewtR workload was caused by register allocation spilling inside Wasmtime’s Cranelift backend. Specific basic-block lowering changes introduced in NetWasm 0.10.8 altered the variable lifetime structure, prompting Cranelift to store an active loop variable in a stack memory slot rather than keeping it inside an available host CPU register.

How does NetWasm handle C# exception throwing without incurring massive Wasmtime register save overhead?

In NetWasm 0.10.1, the compiler refactored exception handling so that all throw paths route through a single, shared helper function. Stack frame preservation and register restoration are deferred to the catching handler during unwinding. This architecture removes local register save-and-restore blocks from normal, checked execution paths, preventing method call overhead.

Sources and further reading

This article was drafted with AI assistance from the publicly cited sources and passed automated checks for structure and sourcing. Verify critical details against the vendor advisories linked above before acting.