[英]C# Code optimization
who could be faster ? 谁会更快? and why ?
为什么?
1: 1:
Point point = new Point(25,25); //any numbers..
Point point2 = new Point(20,95); //any numbers..
Graphics g = CreateGraphics();
g.DrawLine(point,point2);
OR 要么
2: 2:
Graphics g = CreateGraphics();
g.DrawLine(new Point(25,25),new Point(20,95));
None of them, since both snippets will compile to the same MSIL code representation. 它们都不是,因为两个代码片段都将编译为相同的MSIL代码表示形式。
Besides, this is a micro-optimization, which you should avoid before actually knowing that it is the bottleneck. 此外,这是一个微优化,在实际知道这是瓶颈之前,您应该避免这种情况。
两者之间都没有真正的区别,只是可读性下降(特别是在JITing之后)。
Micro Optimization, huh? 微优化,是吗? One notable playwright says code readability is more important than micro optimizations , and I agree.
一位著名剧作家说, 代码的可读性比微优化更重要 ,我同意。
两者都不是更快,最快的就是避免完全在“渲染”路径中分配这些点并提前创建它们的点。
2 might be faster because you're not creating intermediate pointers to the object before passing it to g.DrawLine; 2可能更快,因为在将对象传递给g.DrawLine之前没有创建指向该对象的中间指针; however, if that's the only place you use point and point2 then the compiler will likely optimize so the binary is the same anyway.
但是,如果这是您使用point和point2的唯一位置,则编译器可能会进行优化,因此二进制文件始终是相同的。
It all depends on what else you're doing. 这完全取决于您在做什么。
If you're doing almost nothing else (which I doubt) then this is the "bottleneck". 如果您几乎什么都不做(我怀疑),那么这就是“瓶颈”。
If this is the "bottleneck" then you still don't know what's dominant: 如果这是“瓶颈”,那么您仍然不知道什么是主要的:
two "new"s and associated constructors, destructors, and garbage collection. 两个“ new”以及关联的构造函数,析构函数和垃圾回收。
actually rendering lines. 实际渲染线条。
The second is probably unavoidable, but the first is only there for style reasons. 第二个可能是不可避免的,但第一个仅出于样式原因而存在。
You can find out by profiling or this simple method . 您可以通过分析或这种简单的方法来查找。
Or you can avoid the whole question with: 或者您可以通过以下方法避免整个问题:
g.DrawLine(25,25,20,95);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.