views:

121

answers:

3

Lately, I have taken to the pattern of having a lot of diagnostic logging in parts of my code, that makes use of lambda expressions/anonymous delegates like so:

MyEventManager.LogVerbose( LogCategory.SomeCategory, () => String.Format(msg_string, GetParam1(), GetParam2(), GetParam3() );

Notice that the second argument to LogVerbose is a lambda expression which evaluates to a string. The reason for this is that if verbose logging is not actually enabled, LogVerbose should exit having done as little work as possible, in order to minimize performance impact. The construction of the error message string may, in some cases, take time or resources, and if the lambda expression is never evaluated, that performance penalty will not be incurred.

I'm wondering if littering the type system with so many anonymous delegates like this will have some unforeseen consequence for application performance, or if there are any other strategies I should consider.

+1  A: 

Whilst I don't actually know for sure the answer to the question, I think its worth considering that a drive to a more functional style of programming in C# would be seriously undermined if there were any suggestion that there would some kind of limit on the use of such expressions.

AnthonyWJones
+1  A: 

It should be fine. In particular, if your anonymous function doesn't capture anything, it is cached as a static field (because it can be). If you capture "this" then you'll end up creating new delegate instances, but they're not expensive.

If you capture local variables, that will involve instantiating a nested type - but I'd only worry about this if you saw it actually becoming a problem. As ever with optimisation, focus on readability first, measure the performance, and then profile it to find out where you need to concentrate your efforts.

Jon Skeet
This is what I suspected, that's for the technical justification.
jlew
+1  A: 

I've got a solution that's got thousands of anon delegates, and it still works. Sometimes Visual Studio is a little clunky, but whether that's because we've got hundreds of projects or this or some other factor is unknown. The performance of the applications don't seem to be that strongly affected (with quite a bit of perf testing).

McKay