.NET 性能提示.NET Performance Tips

术语“性能”通常指程序的执行速度。The term performance generally refers to the execution speed of a program. 有时通过遵循源代码中的一些基本规则便可以提高执行速度。You can sometimes increase execution speed by following certain basic rules in your source code. 在某些程序中,十分重要的一点是需要仔细检查代码并使用探查器确保程序尽可能快地运行。In some programs, it is important to examine code closely and use profilers to make sure that it is running as fast as possible. 而在其他程序中,由于代码在编写时便运行得足够快,因此不必执行此类优化。In other programs, you do not have to perform such optimization because the code is running acceptably fast as it is written. 本文列出了一些性能可能遭受影响的常见领域以及相关改进建议,并提供其他性能主题的链接。This article lists some common areas where performance can suffer and tips for improving it as well as links to additional performance topics. 有关规划和测量性能的详细信息,请参阅性能For more information about planning and measuring for performance, see Performance

装箱和取消装箱Boxing and Unboxing

如果值类型必须被频繁装箱,那么在这些情况下最好避免使用值类型(例如在诸如 System.Collections.ArrayList 的非泛型集合类中)。It is best to avoid using value types in situations where they must be boxed a high number of times, for example in non-generic collections classes such as System.Collections.ArrayList. 可通过使用泛型集合(例如 System.Collections.Generic.List<T>)来避免装箱值类型。You can avoid boxing of value types by using generic collections such as System.Collections.Generic.List<T>. 装箱和取消装箱过程需要进行大量的计算。Boxing and unboxing are computationally expensive processes. 对值类型进行装箱时,必须创建一个全新的对象。When a value type is boxed, an entirely new object must be created. 这可能比简单的引用赋值用时最多长 20 倍。This can take up to 20 times longer than a simple reference assignment. 取消装箱的过程所需时间可达赋值操作的四倍。When unboxing, the casting process can take four times as long as an assignment. 有关详细信息,请参阅装箱和取消装箱For more information, see Boxing and Unboxing.

字符串Strings

在连接大量字符串变量时,例如在紧凑循环中,请使用 System.Text.StringBuilder 而不是 C# + 运算符或 Visual Basic 串联运算符When you concatenate a large number of string variables, for example in a tight loop, use System.Text.StringBuilder instead of the C# + operator or the Visual Basic Concatenation Operators. 有关详细信息,请参阅如何在 Visual Basic 中串联多个字符串和串联运算符。For more information, see How to concatenate multiple strings and Concatenation Operators in Visual Basic.

析构函数。Destructors

不应使用空的析构函数。Empty destructors should not be used. 如果类包含析构函数,则 Finalize 队列中会创建一个条目。When a class contains a destructor, an entry is created in the Finalize queue. 调用析构函数时,将调用垃圾回收器来处理此队列。When the destructor is called, the garbage collector is invoked to process the queue. 如果析构函数为空,只会导致性能损失。If the destructor is empty, this simply results in a loss of performance. 有关详细信息,请参阅析构函数对象生存期:如何创建和销毁对象For more information, see Destructors and Object Lifetime: How Objects Are Created and Destroyed.

其他资源Other Resources

另请参阅See also