在明确一段代码会造成真正的瓶颈之前,我不会太在意性能。假设您遇到了这样的瓶颈,并测量以下代码的性能(它在 C# 中,但我很确定 C++ 不会变慢):
public class Rectangle
{
public int X { get; set; }
public int Y { get; set; }
public int W { get; set; }
public int H { get; set; }
public bool HitTest(int x, int y)
{
return x >= X && x < X + W && y >= Y && y < Y + H ? true : false;
}
}
我们对HitTest()
方法的性能感兴趣,所以让我们测量一下吧!
void PerformanceTest()
{
const int Iterations = 1000000;
Random rnd = new Random();
var rectangles = Enumerable.Range(1, 50).Select(
r => new Rectangle {
X = rnd.Next(1000),
Y = rnd.Next(1000),
W = rnd.Next(1000),
H = rnd.Next(1000)}).ToList();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < Iterations; i++)
{
rectangles.ForEach(r => r.HitTest(500, 500));
}
sw.Stop();
Console.WriteLine("Elapsed time: {0}ms. ({1}us per one iteration)",
sw.ElapsedMilliseconds,
(float)sw.ElapsedMilliseconds * 1000 / Iterations);
}
在我的电脑上打印上面的代码:
经过时间:701 毫秒。(每次迭代 0.701us)
如您所见,测试 50 个矩形只需要不到一微秒的时间。与创建花哨的悬停效果以及您的程序所做的其他任何事情相比,您真的认为这太长了吗?当然,只有你能回答这个问题。
但我的故事的寓意是:不要尝试预先优化,也不要花时间尝试解决可能根本不存在的问题。