I noticed on a few projects I'm currently working on that the developers are maniacal about initializing variables. That is, either they initialize them when they're declared:
private string s = null; private int n = 0; private DataSet ds = null;
Or they initialize them in the constructor:
class MyClass
{
private string s;
private int n;
private DataSet ds;
public MyClass()
{
s = null;
n = 0;
ds = null;
}
}
Well, this all struck me as unnecessary work in the .NET world. Sure, maybe that's the convention in the wild and wooly world of buffer overrunsC++, but this is managed code. Do we really want to play the I'm smarter than the runtime game again?
Ok, so maybe you're a masochist and you like extra typing. What about the performance argument? According to this well-researched CodeProject article, initializing variables actually hurts performance. The author provides some benchmark test code along with his results:
| Creating an object and initializing on definition | 11% slower |
| Creating an object and initializing in the constructor | 16% slower |
| Calling a method and initializing variables | 25% slower |
That's on the author's Pentium-M 1.6ghz. I tested the same code (optimizations enabled, release mode) on my Athlon 64 2.1ghz and a Prescott P4 2.8ghz:
| Athlon 64 | P4 | |
| Creating an object and initializing on definition | 30% slower | 35% slower |
| Creating an object and initializing in the constructor | 30% slower | 36% slower |
| Calling a method and initializing variables | 14% slower | 8% slower |
I recompiled under VS.NET 2005 beta 2 using the Athlon 64 to see how .NET 2.0 handles this:
| Creating an object and initializing on definition | 0% slower |
| Creating an object and initializing in the constructor | 20 % slower |
| Calling a method and initializing variables | 20% slower |
Clearly there's a substantial performance penalty for initializing variables in both .NET 1.1 and even .NET 2.0 (although the newer compiler appears to optimize away initialization on definition). I recommend avoiding initialization as a general rule, unless you have a compelling reason to do so. If you're only initializing variables to avoid the uninitialized variable compiler warning, check out the new #pragma warning feature to programmatically disable specific warnings in .NET 2.0.
Posted by Jeff Atwood View blog reactions
« Passwords vs. Pass Phrases On Being Pushy »
A .NET compiler should never give an "uninitialized variable" warning except for autos. I do use explicit init values when the variable is some sort of specific numeric value, for example the lower end of a range, even if it's zero. Makes the code easier to read.
C# 2.0 does indeed strip out variable initializers that merely duplicate the runtime default value; that's what Gunnerson & Wienholt are saying, anyway ("A Programmer's Introduction to C# 2.0", Apress).
Initializing in ctors and methods probably can never be optimized away since the compiler or runtime cannot generally know what the variable values are when the method is called. Even if a given chunk of code can be statically analyzed, someone else might derive another type or use reflection from another assembly to call those methods...
Chris Nahr on July 20, 2005 02:41 AMIndeed you do get a performance hit for doing so. I think FxCop catches these unnecessary initializations and reports them.
Raymond Lewallen on July 20, 2005 09:38 AMA lot of us have had variable initialization drilled into us, so it can be a hard habit to break. I have gotten better though.
What really sucks though is that a local variable must be initialized(at least in C#). For example, this snippet will cause a compiler error:
MyObject obj;
if(condition)
obj = new MyObject();
return obj;
So, in my mind, we have two conflicting messages being conveyed. I know the difference between the two cases, but I'm not sure I understand why the object gets implicitly set to null in one case but not in the other. In the example I posted, null might be a perfectly acceptable return value, but I would have to append an " = null; " on it to keep the compiler from complaining.
Marty Thompson on July 20, 2005 10:09 AMReporting the slowdowns as a percentage makes them seem much more important than they may be. ;)
"35% slower" sounds much worse than "It took 0.00003ms per operation rather than 0.0000195ms"
So rather than just focusing on the performance difference, which should really only matter if you notice the difference in your application, think about the other side of the argument. Are there any benefits to initializing your vars other than taking away the nag error?
Scott on July 20, 2005 01:25 PMargh, I hit post too quickly. hehe
My point isn't that it's better to initialize your vars, just that the cost-benefits analysis needs to be done for any performance tip. I'm looking over my code and I'm not initializing anything anywhere. Which means I was ahead of the game. I'm going to use that to further my "when you shouldn't listen to advice from people" rule-of-thumb; which includes "before getting married", "before the birth of your first child", and "when programming". ;)
Scott on July 20, 2005 01:30 PMI disagree there. Do please initialize your variables, at least in the constructor. If a C++, C, Java or Cobol coder has a look on your C# code, he may wonder "which value may get this var during run ?". We need also to get rid with this horrible "string.Empty" or "Null" confusions.
Um, the C++, C, Java or Cobol coder should learn C# if he's going to maintain C# code. Default null inits are part of the standard, and anyone touching the code can be expected to know this. Or maybe we should all avoid using classes and inheritance since a FORTRAN IV coder might not know such constructs?
Chris Nahr on July 21, 2005 10:15 AM> Reporting the slowdowns as a percentage makes them seem much more important than they may be. ;)
Of course; I wasn't trying to artificially inflate the performance rationale. The main reason not to do it is because it's more unnecessary code that has to be debugged and read by someone. The perf benefits are just a bonus.
Jeff Atwood on July 21, 2005 11:29 PMIn .NET 2.0 the compiler, when set to optimize code, removes redundant variable initialization.
Shaun Random on November 22, 2005 12:29 AMi think it's a good idea to initialize ALL variables, even if u know that there is no need in doing that
the main reason of doing so is my paranoidal programmer's aspiration 4 maximum safety of written code
initializin' variables is after all a good style of coding, i think: it works anywhere & always
PS: some coders don't bother themselves with initializing variables, setting checks etc - sooner or later it makes their code unstable...
vo1d on July 10, 2006 12:35 AMIf you're worried about performance you won't be using c# so initialise your variables and if your code is too slow get a bigger box or use C++!
Ian on July 12, 2006 02:02 AMgood
mer on May 19, 2008 05:40 AM| Content (c) 2008 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved. |