2

在 .Net Compact Framework 中绘制一些形状时,我发现了一些令人惊讶的结果。

Method1 和 Method2 绘制了一些矩形,但是 Method1 比 Method2 快,这里是代码:

方法1:

int height = Height;
for (int i = 0; i < data.Length; i++)
{
  barYPos = Helper.GetPixelValue(Point1, Point2, data[i]);

  barRect.X = barXPos;
  barRect.Y = barYPos;
  barRect.Height = height - barYPos;
  //
  //rects.Add(barRect);
  _gBmp.FillRectangle(_barBrush, barRect);
  //
  barXPos += (WidthOfBar + DistanceBetweenBars);
} 

方法2:

for (int i = 0; i < data.Length; i++)
{
  barYPos = Helper.GetPixelValue(Point1, Point2, data[i]);

  barRect.X = barXPos;
  barRect.Y = barYPos;
  barRect.Height = Height - barYPos;
  //
  //rects.Add(barRect);
  _gBmp.FillRectangle(_barBrush, barRect);
  //
  barXPos += (WidthOfBar + DistanceBetweenBars);
} 

两者之间的唯一区别在于Method1我将Height控件存储在局部变量中。

谁能解释一下.Net Compact Framework中绘图的原因和一些指导方针?

4

3 回答 3

3

方法 2 较慢,因为您在 for 循环的每次迭代中都访问 Height 属性。此属性可能会导致一些耗时的计算,并将其放在循环外的局部变量中充当缓存。

于 2012-07-27T12:35:16.187 回答
1

在 C# 中调用属性比直接访问内存中的变量具有更多的相关成本;因为属性是作为在后台具有支持字段的方法生成的(和/或更糟..也许它会查询其他东西!)

如果您的应用程序确实是单线程的并且您有能力缓存它,那么就这样做。避免紧密循环中的属性。

于 2012-07-27T12:51:38.393 回答
0

我相信那是因为您访问了Height-data.Lenght很多次。并且在第一个方法中,您只需将其初始化一次。

于 2012-07-27T12:35:25.580 回答