Brushes.White slows graphics demo down

て烟熏妆下的殇ゞ 提交于 2019-12-05 03:27:19
Jaska

Because new Color() has alpha value of zero, which means WPF doesn't have to render it because it's fully transparent - on the other hand White color's alpha is 255, which means it is completely solid white color which have to be rendered.

Bryce Wagner

There is nothing special about using Brushes.White.

If you define your own local brush outside the macroStep event handler, and then freeze it, it will behave exactly identical to using Brushes.White. If you don't freeze it first, it will behave far, far worse.

The best performance is to create your brush once at the beginning of each call to macroStep, before the loop, and then freeze it. It is a significant slowdown if you create a new brush inside the innermost loop.

Also, if you increase the interval on the timer for the badly behaving code, it will actually fix the performance issue. My guess is that there's some kind of resource cleanup that would occur on a background thread after it finishes rendering each time, that's tied to the internals of the brush, but it's starved from being able to do its cleanup because you're turning right around and using the brush in the next iteration. To demonstrate this, I created a pool of brushes, and use a different brush each time:

SolidColorBrush[] brushes = new SolidColorBrush[2];
for (int i = 0; i < brushes.Length; i++)
{
    var brush = new SolidColorBrush(new Color());
    brush.Freeze();
    brushes[i] = brush;
}
int brushIx = 0;

Action macroStep = () =>
{
    dataB = new int[100, 100];
    var brush = brushes[brushIx++ % brushes.Length];
...
    rectangles[x, y].Fill = dataB[x, y] == 0
        ? brush
        : Brushes.Black;
    data = dataB;
};

If you set the number of brushes to 1, this will give the same behavior as using Brushes.White. But if you set it to 2 or more, you'll get the performance you expect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!