ASP.NET Core Blazor WebAssembly performance best practices

By Pranav Krishnamoorthy

This article provides guidelines for ASP.NET Core Blazor WebAssembly performance best practices.

Avoid unnecessary component renders

Blazor's diffing algorithm avoids rerendering a component when the algorithm perceives that the component hasn't changed. Override ComponentBase.ShouldRender for fine-grained control over component rendering.

If authoring a UI-only component that never changes after the initial render, configure ShouldRender to return false:

@code {
    protected override bool ShouldRender() => false;
}

Most apps don't require fine-grained control, but ShouldRender can be used to selectively render a component responding to a UI event. Using ShouldRender might also be important in scenarios where a large number of components are rendered. Consider a grid, where use of EventCallback in one component in one cell of the grid calls StateHasChanged on the grid. Calling StateHasChanged causes a re-render of every child component. If only a small number of cells require rerendering, use ShouldRender to avoid the performance penalty of unnecessary renders.

In the following example:

  • ShouldRender is overridden and set to the value of the ShouldRender field, which is initially false when the component loads.
  • When the button is selected, ShouldRender is set to true, which forces the component to rerender with the updated currentCount.
  • Immediately after rerendering, OnAfterRender sets the value of ShouldRender back to false to prevent further rerendering until the next time the button is selected.
<p>Current count: @currentCount</p>

<button @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;
    private bool shouldRender;

    protected override bool ShouldRender() => shouldRender;

    protected override void OnAfterRender(bool first)
    {
        shouldRender = false;
    }

    private void IncrementCount()
    {
        currentCount++;
        shouldRender = true;
    }
}

For more information, see ASP.NET Core Blazor lifecycle.

Virtualize re-usable fragments

Components offer a convenient approach to produce re-usable fragments of code and markup. In general, we recommend authoring individual components that best align with the app's requirements. One caveat is that each additional child component contributes to the total time it takes to render a parent component. For most apps, the additional overhead is negligible. Apps that produce a large number of components should consider using strategies to reduce processing overhead, such as limiting the number of rendered components.

For example, a grid or list that renders hundreds of rows containing components is processor intensive to render. Consider virtualizing a grid or list layout so that only a subset of the components is rendered at any given time. For an example of component subset rendering, see the following components in the Virtualization sample app (aspnet/samples GitHub repository):

  • Virtualize component (Shared/Virtualize.razor): A component written in C# that implements ComponentBase to render a set of weather data rows based on user scrolling.
  • FetchData component (Pages/FetchData.razor): Uses the Virtualize component to display 25 rows of weather data at a time.

Avoid JavaScript interop to marshal data

In Blazor WebAssembly, a JavaScript (JS) interop call must traverse the WebAssembly-JS boundary. Serializing and deserializing content across the two contexts creates processing overhead for the app. Frequent JS interop calls often adversely affects performance. To reduce the marshalling of data across the boundary, determine if the app can consolidate many small payloads into a single large payload to avoid the high volume of context switching between WebAssembly and JS.

Use System.Text.Json

Blazor's JS interop implementation relies on System.Text.Json, which is a high-performance JSON serialization library with low memory allocation. Using System.Text.Json doesn't result in additional app payload size over adding one or more alternate JSON libraries.

For migration guidance, see How to migrate from Newtonsoft.Json to System.Text.Json.

Use synchronous and unmarshalled JS interop APIs where appropriate

Blazor WebAssembly offers two additional versions of IJSRuntime over the single version available to Blazor Server apps:

  • IJSInProcessRuntime allows invoking JS interop calls synchronously, which has less overhead than the asynchronous versions:

    @inject IJSRuntime JS
    
    @code {
        protected override void OnInitialized()
        {
            var jsInProcess = (IJSInProcessRuntime)JS;
    
            var value = jsInProcess.Invoke<string>("jsInteropCall");
        }
    }
    
  • WebAssemblyJSRuntime permits unmarshalled JS interop calls:

    function jsInteropCall() {
      return BINDING.js_to_mono_obj("Hello world");
    }
    
    @inject IJSRuntime JS
    
    @code {
        protected override void OnInitialized()
        {
            var jsInProcess = (WebAssemblyJSRuntime)JS;
    
            var value = jsInProcess.InvokeUnmarshalled<string>("jsInteropCall");
        }
    }
    

    Warning

    While using WebAssemblyJSRuntime has the least overhead of the JS interop approaches, the JavaScript APIs required to interact with these APIs are currently undocumented and subject to breaking changes in future releases.

Reduce app size

Intermediate Language (IL) linking

Linking a Blazor WebAssembly app reduces the app's size by trimming unused code in the app's binaries. By default, the linker is only enabled when building in Release configuration. To benefit from this, publish the app for deployment using the dotnet publish command with the -c|--configuration option set to Release:

dotnet publish -c Release

Compression

When a Blazor WebAssembly app is published, the output is statically compressed during publish to reduce the app's size and remove the overhead for runtime compression. Blazor relies on the server to perform content negotation and serve statically-compressed files.

After an app is deployed, verify that the app serves compressed files. Inspect the Network tab in a browser's Developer Tools and verify that the files are served with Content-Encoding: br or Content-Encoding: gz. If the host isn't serving compressed files, follow the instructions in Host and deploy ASP.NET Core Blazor WebAssembly.

Disable unused features

Blazor WebAssembly's runtime includes the following .NET features that can be disabled if the app doesn't require them for a smaller payload size:

  • A data file is included to make timezone information correct. If the app doesn't require this feature, consider disabling it by setting the BlazorEnableTimeZoneSupport MSBuild property in the app's project file to false:

    <PropertyGroup>
      <BlazorEnableTimeZoneSupport>false</BlazorEnableTimeZoneSupport>
    </PropertyGroup>
    
  • Collation information is included to make APIs such as StringComparison.InvariantCultureIgnoreCase work correctly. If you're certain that the app doesn't require the collation data, consider disabling it by setting the BlazorWebAssemblyPreserveCollationData MSBuild property in the app's project file to false:

    <PropertyGroup>
      <BlazorWebAssemblyPreserveCollationData>false</BlazorWebAssemblyPreserveCollationData>
    </PropertyGroup>