28. August 2011 11:23
Not long ago I blogged how to reduce build time when using Code Analysis. Even though the method gives you 20 - 30% faster build times you end up with half-assed fix for the actual problem. You end up completely disabling rules like CA2000 Dispose objects before losing scope or CA2241 Provide correct arguments to formatting methods. Once you take that road then why not disable some other rules to gain more speed?
Instead of disabling rules one by one I decided to go another route - running code analysis when I want instead of automatically. First it sounded complicated and I was sure I had to manually modify project files. Then I remembered that Visual Studio supports this kind of thing out of the box. The feature is called Solution Configurations (or Build Configurations).
Creating new configuration for Code Analysis
First we are going to create new solution configuration. Select your solution and from the context menu choose Configuration Manager...
In the Configuration Manager window you'll see existing configurations. For pure .NET projects there is usually Debug/Release. From the active solution configuration select New…
We are going to name our configuration as CA Debug and copy all settings from the existing Debug configuration.
After that you can see the newly created CA Debug in the list of active solution configurations. You can now close the Configuration Manager.
All you have to do is to modify your project settings to run the Code Analysis when CA Debug configuration is used.
When you are developing your software you can use the normal Debug configuration and keep the fast build times. When you want to run code analysis just switch to the new configuration and build.
Pros and Cons
There are pros and cons for using this method:
- Pro: build times are fast. With my example solution the difference between “No Code Analysis” and “Full Code Analysis” was huge. With huge I mean building without code analysis took 7,5 seconds and with full rule set it took 32,3 seconds. That is huge difference when you are building often.
- Pro: Your warning/error list is not filled with code analysis warnings every time you build. If I’m just writing the code I know there are going to be things that are not perfect. I don’t need constant reminder of that.
- Con: You have to remember to use the new configuration every now and then. You will forget to do that but that is why your CI build should be configured to use code analysis.
- Con: If you run the code analysis once a day you might end up with design/code that you have to change a lot because of the warnings. In my opinion this is pretty rare.
In my opinion the pros outweigh the cons.