Open Khiro95 opened 9 months ago
At the moment, I'm using this extension method as a workaround for my specific case:
public static Rect GetBoundsFast(this System.Windows.Media.Geometry geometry)
{
if (geometry is StreamGeometry sg)
{
return sg.Bounds;
}
else if (geometry is GeometryGroup gg)
{
Rect rect = Rect.Empty;
foreach (var g in gg.Children)
{
rect.Union(g.GetBoundsFast());
}
rect.Transform(gg.Transform.Value);
return rect;
}
throw new ArgumentException();
}
It cuts down my processing function time from 3 minutes to just 11 seconds!
Background
I'm working on a project where I need to handle thousands of geometry shapes and most operations applied are merging/combining and transforming. I start from using
StreamGeometry
and then useGeometryGroup
when I need to apply general transform for multiple geometries at once. But since I rely too much onBounds
property, mainly for custom positioning and scaling, I noticed that the app take longer time compared to other project which usesImageSharp
(it does same job but not Windows-dependent).At this point, I used Performance Profiler and found
get_Bounds()
in hot paths take a lot of CPU time.Benchmark
I decided to benchmark the property and see how much impact it has on performance, so here is the setup:
GeometryBoundsBenchmark.csproj
Program.cs
Run command
Results
As you can see,
GeometryGroup.Bounds
allocates too many objects and is almost 900 times slower thanStreamGeometry.Bounds
which is only 11 times slower than cached value.Expected behavior
I expect
GeometryGroup.Bounds
to not be that much slow, especially when it's frozen and its children are frozen as well.My question
Is this behavior normal?! If so, what are the suggestions to avoid this bottleneck.
Thank you.