C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Directives: For long blocks of commented text, a directive like #if-false can be used.
C# program that uses comments
using System;
class Program
{
static void Main()
{
// An example comment.
// ... Sometimes indenting comments is helpful too.
int value = 10; // Ten.
/*
A multi-line comment.
*/
value++;
#if false
Another way to comment, an #if false directive.
#endif
value *= 100;
Console.WriteLine(value);
}
}
Output
1100
C# program that uses XML comments
using System;
class Program
{
/// <summary>
/// Test value and modify it.
/// </summary>
/// <param name="value">The important value.</param>
/// <returns>The modified value.</returns>
static int Test(int value)
{
return value * 2;
}
static void Main()
{
Console.WriteLine(Test(2));
}
}
Output
4
Here: The two methods are identical except that the first has no comments and the second has almost 20 lines of comments on it.
So: By testing these two methods, we can show what effect comments in methods has on execution performance.
C# program that tests comments
class Program
{
static void Increment()
{
int value = 0;
for (int i = 0; i < 100000; i++)
{
for (int j = 0; j < 10; j++)
{
value++;
}
}
_field = value;
}
static void IncrementWithComments()
{
// Local variable in variable slot that is incremented.
int value = 0;
// Loop through the first one-hundred thousand numbers.
for (int i = 0; i < 100000; i++)
{
// Nested loop through first ten numbers.
for (int j = 0; j < 10; j++)
{
// Increment the variable once.
value++;
}
}
// Store local variable's value in static field.
_field = value;
}
static int _field;
static void Main()
{
Increment();
IncrementWithComments();
}
}
Output
Increment: 0.331 ms (uncommented release)
IncrementWithComments: 0.330 ms (commented release)
Increment: 0.308 ms (uncommented debug, fewer iterations)
IncrementWithComments: 0.308 ms (commented release, fewer iterations)
Result: The times measured were close for both the uncommented and commented versions of the methods.
Tip: At this point, the compiler can remove all lines beginning with the // characters and text between the /* and */ delimiters.
And: Because of this phase, the compiled DLL from the C# code contains no trace of the comments.
Tip: The book Code Complete by Steve McConnell contains a large chapter on commenting strategies.
Info: This code will have no comments or local variable names because these were removed.