开发者

Speeding up the execution of C#/.NET application [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago. 开发者_JAVA百科

I'm searching for methods to boost up C#/.NET application. What I found so far is

  1. Use ngen.
  2. Careful when using as operator
  3. Careful when using reflection API. It takes quite a while to load dll with Assembly.LoadFrom().

What else tools/tips/good practices do you have to get the best performance out of C#/.NET program.


First be careful with ngen. It might actually end up hurting performance. See Jeff Richter's book "CLR via C#, Third Edition" for more details.

Personally I will use a profiler when I need to performance tune my application. The one I prefer is Red-Gate Ants, but there are plenty of good ones on the market. However using these can be a bit tricky because they will produce a lot of noise.

Most of the problems I have seen are usually caused by the developer or overall architecture rather than the .Net Framework. For example an Asp.Net web application that requires 30+ calls to the Database just for the home page to load.


Memoize expensive functions when possible.

public static class Expensive
{
    private static readonly ConcurrentDictionary<int, int> _map = 
        new ConcurrentDictionary<int, int>();

    public static int Calculate(int n)
    {
        return _map.AddOrUpdate(n, Add, (key, value) => value);
    }

    static int Add(int key)
    {
        return 0;
    }
}


You should not use ngen until you precisely know what CPU environment your dlls are going to be deployed on. And know for sure that they will not be deployed on other CPU types. It is bad if you compile to x86 native and deploy on x64. You will lose all the optimizations the compiler could have done JIT.

Performance depends on what your application is trying to do. The guidelines would be very different if it was a db driven web app vs a desktop music player app. But you should be looking to avoid boxing/unboxing, lots of reflection, using XmlDocument to load up a very large Xml doc, and use the inbuilt CLR ThreadPool class to do multi-threading, remember to implement IDisposable to name a few..


I once spent several days rewriting code to speed up the application, when in fact I found out there was a bottleneck in my CompareTo implementation which was being called thousands of times.

  • Use a profiler.
  • Don't waste time optimizing what doesn't matter (in your case).
  • Find out what does.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜