Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DrawingContext.DrawLine performance problem

Tags:

wpf

I was trying out different strategies for drawing a graph from the left edge of a control to the right edge. Until now we were using a Canvas with a polyline which performs OK, but could still use some improvement.

When I tried out DrawingContext.DrawLine I experienced incredibly bad performance, and I can't figure out why. This is the most condensed code I can come up with that demonstrates the problem:

public class TestControl : Control {

    static Pen pen = new Pen(Brushes.Gray, 1.0);
    static Random rnd = new Random();

    protected override void OnRender(DrawingContext drawingContext) {

        var previousPoint = new Point(0, 0);

        for (int x = 4; x < this.ActualWidth; x += 4) {
            var newPoint = new Point(x, rnd.Next((int)this.ActualHeight));
            drawingContext.DrawLine(pen, previousPoint, newPoint);
            previousPoint = newPoint;
        }
    }
}

And MainWindow.xaml just contains this:

<StackPanel>
    <l:TestControl Height="16"/>
    <!-- copy+paste the above line a few times -->
</StackPanel>

Now resize the window: depending on the number of TestControls in the StackPanel I experience a noticeable delay (10 controls) or a 30-second-total-standstill (100 controls) where I can't even hit the "Stop Debugger"-Button in VS...

I'm quite confused about this, obviously I am doing something wrong but since the code is so simple I don't see what that could be... I am using .Net4 in case it matters.

like image 396
wilford Avatar asked May 09 '11 13:05

wilford


1 Answers

You can gain performance by freezing the pen.

static TestControl()
{
    pen.Freeze();
}
like image 172
Marat Khasanov Avatar answered Sep 23 '22 21:09

Marat Khasanov