Does it decrease performance or is it bad practice if I create scopes which aren't necessary? By that I mean, creating scopes just for readability:
XmlElement header = list[0] as XmlElement;
if (header == null) throw new Exception("Corrupt header.");
{
XmlElement subHeader = null; // ...
}
This way it is cleary better readable. Any reasons why to avoid this? I just realized this would be quite nice to make my relatively long code a bit more readable. Especially because this happens more than once that I have to load a main element which then has some sub elements I could easily separate visually.
What do the Pros say?
This isn't more readable. Your example code shows this.
In my mind the difference between these two sets of code is confusing:
XmlElement header = list[0] as XmlElement;
if (header == null)
{
XmlElement subHeader = null; // ...
}
XmlElement header = list[0] as XmlElement;
if (header == null) throw new Exception("Corrupt header.");
{
XmlElement subHeader = null; // ...
}
Also, if your code is "relatively long" then it should be broken down into separate methods and not grouped by scope blocks.
Now, as far as performance goes. Here's a simple example:
var text = "Hello";
Console.WriteLine(text);
This turns into this IL:
IL_0001: ldstr "Hello"
IL_0006: stloc.0 // text
IL_0007: ldloc.0 // text
IL_0008: call System.Console.WriteLine
If I write the code like this:
var text = "Hello";
{
Console.WriteLine(text);
}
The IL becomes:
IL_0001: ldstr "Hello"
IL_0006: stloc.0 // text
IL_0007: nop
IL_0008: ldloc.0 // text
IL_0009: call System.Console.WriteLine
IL_000E: nop
Note the nop
operations.
For every scope block I get a new pair of nop
operations in the IL. But this only happens in debug mode. In release mode the nop
operations are removed.
To test the performance difference in debug mode I wrote this code:
var sw = Stopwatch.StartNew();
var x = 0L;
for (var y = 0; y < 1000000000L; y++)
{
{
x += y;
}
}
sw.Stop();
Console.WriteLine(x);
Console.WriteLine(sw.ElapsedMilliseconds);
With the extra scope it ran consistently in about 3,550 ms. Without the extra scope is was about 3,500 ms. So about 1.5% difference in performance. And this is only in debug mode!
But considering that my operation x += y
is so trivial and the performance drop so miniscule that you could probably just ignore the performance difference in normal code. And obviously ignore it entirely in release mode code.