menu_bookDocumentation
BuildHash pattern for Razor panel optimization
BuildHash Pattern for Razor Panel Optimization
BuildHash is a method you can override in Razor panels to prevent unnecessary rebuilds when the underlying state hasn't changed. This is critical for performance in panels that update frequently.
How It Works
When you call StateHasChanged(), s&box checks if the BuildHash has changed since the last render. If the hash is the same, the render is skipped.
Basic Pattern
CSHARP
protected override int BuildHash() => HashCode.Combine(inventory, activeSlot, Player?.WantsHideHud);Example: Inventory Panel
CSHARP
@inherits PanelComponent
@code
{
PlayerInventory inventory;
int activeSlot = -1;
protected override int BuildHash() => HashCode.Combine(inventory, activeSlot, Player?.WantsHideHud);
protected override void OnUpdate()
{
inventory = Game.ActiveScene.GetAllComponents<PlayerInventory>()
.Where(x => x.Network.IsOwner).FirstOrDefault();
activeSlot = inventory?.ActiveWeapon?.InventorySlot ?? -1;
}
}When to Use BuildHash
Use BuildHash in panels that:
- Update frequently (every frame in OnUpdate or Tick)
- Display data that changes often
- Have complex markup that's expensive to rebuild
- Are performance-critical (HUD, inventory, spawn menu)
What to Include in BuildHash
Include all values that affect the panel's rendering:
- State variables (inventory, activeSlot, etc.)
- Player state (WantsHideHud, health, ammo)
- Configuration values
- Any data displayed in the markup
Common Mistakes
- Not including all state: If you forget a variable, the panel won't update when it changes
- Including too much: Including values that don't affect rendering causes unnecessary rebuilds
- Not using it at all: Panels that update every frame without BuildHash will rebuild constantly
Performance Impact
Without BuildHash, a panel updating at 60 FPS will rebuild 60 times per second. With BuildHash, it only rebuilds when state actually changes, which can be a massive performance improvement.
Notes
- BuildHash is optional but highly recommended for performance-critical panels
- Use HashCode.Combine() to combine multiple values into a single hash
- The hash is computed every frame, so keep it fast (avoid expensive operations)
- For simple panels that rarely change, BuildHash may not be necessary
Was this helpful?