How do you check your renders?
Here's my method
Create a base class that inherits ComponentBase, override ShouldRender and OnAfterRender to start and stop the Stopwatch, and keep track of how many renders there have been.
public class PerfTestBase : ComponentBase
{
Stopwatch Stopwatch = new Stopwatch();
int RenderCount =0;
protected override bool ShouldRender()
{
Stopwatch.Start();
RenderCount++;
return base.ShouldRender();
}
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
Stopwatch.Stop();
Console.WriteLine($"{GetType().Name} : Render #{RenderCount} Duration {Stopwatch.ElapsedMilliseconds}");
}
}
Add @inherits PerfTestBase
to your _Imports.razor
to make every component that doesn't already inherit a base class use this one.
If you already use a base class, maybe consider just adding these bits to it while perf testing.
Now, you will see log messages in your console for every Component render, like this:
App : Render #0 Duration 0
Navbar : Render #0 Duration 0
ChatRoomList : Render #0 Duration 0
Index : Render #0 Duration 0
Fetching gitter user.
Navbar : Render #1 Duration 0
ChatRoomList : Render #1 Duration 0
Index : Render #1 Duration 1
ChatRoomList : Render #2 Duration 42
ChatRoomList : Render #3 Duration 87
Navbar : Render #2 Duration 1
ChatRoomList : Render #4 Duration 127
RoomTitle : Render #0 Duration 0
RoomMessages : Render #0 Duration 0
RoomSend : Render #0 Duration 0
RoomSearch : Render #0 Duration 0
RoomMessages : Render #1 Duration 33
20 Message : Render #0 Duration 0
RoomTitle : Render #1 Duration 25
RoomMessages : Render #2 Duration 58
RoomMessages : Render #3 Duration 60
It's now simple to locate Components that render too often or take too long to render.
Goes away to fix ChatRoomList - it looks slow...
Don't leave this in your production build - it will slow things down!