The Problem Solver

Tell me and I will forget
Show me and I will remember
Involve me and I will understand
- Confucius -

Google Ads

This Blog

Syndication

Search

Tags

News





  • View Maurice De Beijer's profile on LinkedIn

Community

Email Notifications

Explore

Archives

Cool attribute Diagnostics.Conditional
Something I often see in code is that parts of it are contained in the following construct:
#If DEBUG Then
   ' Some code
#End If
 
Nothing wrong with that but often the code is the complete function body leaving an empty function in release mode. Now the JIT optimizer will make short work of it so there isn't a big performance penalty but why make it go through these steps in the first place.
 
Another way way of doing so is using the Diagnostics.Conditional attribute. This can be applied to some function and removes all calls to it, so much nicer Smile
 
<Diagnostics.Conditional("DEBUG")> _
Public Sub OnlyHereInDebugMode()
   ' Some code
End Sub
 
To see that the function call is really removed just open reflector and compare the release and debug builds.
 
Enjoy!
 
Published Wed, Feb 14 2007 20:06 by Maurice
Filed under: ,

Comments

# re: Cool attribute Diagnostics.Conditional@ Thursday, February 15, 2007 4:19 AM

No disagreement, just wanted to add :)

There is nothing stopping you wrapping the entire method with #if, not just the body. Also the advantage of #if is that the code doesn't have to be compilable. Witht he attribute, your code must be compilable in the first place.

The main advantage of Conditional is that it can be applied at the called method only without having to surround all the call sites with #if as well...

# re: Cool attribute Diagnostics.Conditional@ Thursday, February 15, 2007 12:02 PM

You are completely right and that works. The thing about removing the complete function using #IF is that, as you point out, you need to do the same with every call. And forgetting one or more doesn't give a compile error until you switch to release build. Now these errors aren't hard to fix but I dislike the idea that just switching from a debug to a release build van cause errors.

by Maurice

# re: Cool attribute Diagnostics.Conditional@ Tuesday, February 26, 2008 10:08 AM

These methods still get compiled though and can be found and called at runtime using reflection.

by Matt

# re: Cool attribute Diagnostics.Conditional@ Tuesday, February 26, 2008 10:19 AM

Hi Matt,

You are completely right, the only thing removed is the actual function call itself.

by Maurice