简体   繁体   中英

C# Code optimization

who could be faster ? and why ?

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:

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.

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; 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.

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.

  • 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM