Archive for the ‘.Net Performance’ Category

A Few .Net (2.0) Notes

Sunday, June 24th, 2007

I am currently brushing up on my .Net skills so I will be taking notes on topics that are worth taking the extra time to remember.

Classes and structs

A class is allocated on the managed heap rather than on the stack and assignment between two variables results in both variables pointing to the same instance.

While the functionality is similar, structures are usually more efficient than classes. A struct takes up the amount of space (on the stack) that the value types defined in the struct take up together. You should define a structure, rather than a class, if the type will perform better as a value type than a reference type. Specifically, structure types should meet all of these criteria: Logically represents a single value; Has an instance size less than 16 bytes; Will not be changed after creation; Will not be cast to a reference type.


The runtime optimizes the performance of 32-bit integer types (Int32 and UInt32), so use those types for counters and other frequently accessed integral variables. For floating-point operations, Double is the most efficient type because those operations are optimized by hardware.


Immutable types in .Net, such as strings: Any change to this type causes the runtime to create a new object and abandon the old one. That happens invisibly, and many programmers might be surprised to learn that the following code allocates four new strings in memory:

1
2
3
4
5
6
7
// C#
string s;
s = "wombat";          // "wombat"
s += " kangaroo";      // "wombat kangaroo"
s += " wallaby";       // "wombat kangaroo wallaby"
s += " koala";         // "wombat kangaroo wallaby koala"
Console.WriteLine(s);

Only the last string has a reference; the other three will be disposed of during garbage collection. Avoiding these types of temporary strings helps avoid unnecessary garbage collection, which improves performance.


These notes have been “borrowed” and modified from the book: MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework 2.0 Application Development Foundation