Consider the following code:
if (IsDebuggingEnabled) { instance.Log(GetDetailedDebugInfo()); }
GetDetailedDebugInfo() can be an expensive method, so we only want to call it if we are in debug mode.
Now a cleaner alternative is code, for example:
instance.Log(() => GetDetailedDebugInfo());
Where .Log () is defined as:
public void Log(Func<string> getMessage) { if (IsDebuggingEnabled) { LogInternal(getMessage.Invoke()); } }
My concern for performance, preliminary testing does not show that the second case will be especially expensive, but I do not want to encounter surprises when the load increases.
Oh, and please do not offer conditional compilation because this is not the case.
(PS: I wrote the code directly in the StackOverflow Ask a Question text box, so don't blame me if there are subtle errors and it doesn't compile, you get the point :)
andreialecu Aug 13 '09 at 0:33 2009-08-13 00:33
source share