Code Issues – Redundant field initialization
The redundant field initialization code issue of type ‘dead code‘ highlights unecessary initialization of fields that can be safely removed (because the common language runtime initializes all fields to their default values, regardless of their type). Value types are initialized to 0 and reference types are initialized to null. Explicitly initializing a field to its default value is redundant, degrades performance and adds to maintenance costs.
When you expressly initialize your fields, the compiler creates code to set the value of the fields and includes that code as part of your object initialization. When you instantiate an object using the new keyword, the following sequence happens:
- Your fields are allocated
- The fields are initialized by the CLR
- The code for the object constructor is performed
The problem is that if you explicitly initialized your fields, the constructor code will initialize your variables twice. This is not a big deal in most cases, but if those objects are instantiated many times, the performance impact may be noticeable.
Performing these kinds of tests when fields are initialized explicitly, shows the following result:
- Creating an object and not initializing fields ~1013 ms (100%)
- Creating an object and explictly initializing fields ~1124 ms (110%)
As you can see, there may be a noticeable performance hit.
How to fix:
- Apply the Remove Redundant Assignment code fix:
—– Products: CodeRush Pro Versions: 12.1 and up VS IDEs: any Updated: Nov/12/2012 ID: C100