Currently, I have a static factory method like this:
public static Book Create(BookCode code) {
if (code == BookCode.Harry) return new Book(BookResource.Harry);
if (code == BookCode.Julian) return new Book(BookResource.Julian);
// etc.
}
The reason I don't cache them in any way is because BookResource is sensitive to culture, which can change between the calls. The changes to culture needs to reflect in the returned book objects.
Doing those if-statements is possible a speed bottleneck. But what if we map book codes to anonymous functions/delegates? Something like the following:
delegate Book Create();
private static Dictionary<BookCode, Delegate> ctorsByCode = new Dictionary<BookCode, Delegate>();
// Set the following somewhere
// not working!
ctorsByCode[BookCode.Harry] = Create () => { return new Book(BookResource.Harry); }
// not working!
ctorsByCode[BookCode.Julian] = Create () => { return new Book(BookResource.Julian); }
public static Book Create(BookCode code) {
return (Book)ctorsByCode[code].DynamicInvoke(null);
}
How could I get those Create() => {
lines to actually work?
Is this worth it speed-wise, when there are <50 book codes (thus <50 if-statements)?
This is a similar question, but unfortunately the author doesn't post his code Enum, Delegate Dictionary collection where delegate points to an overloaded method
Update
Did some performance benchmarks ifs vs delegates. I picked the unit code randomly and used the same seed for both methods. The delegate version is actually slightly slower. Those delegates are causing some kind of overhead. I used release builds for the runs.
5000000 iterations
CreateFromCodeIf ~ 9780ms
CreateFromCodeDelegate ~ 9990ms
Like this:
The
Func<Book>
type is a pre-defined generic delegate type that you can use instead of creating your own.Also, your dictionary must contain specific a delegate type, not the base
Delegate
class.Although lambda expressions are untyped expressions, they can be used in a place where a delegate type is expected (such as your indexer assignment) and will implicitly assume the type of the delegate.
You could also write
I would recommend changing your dictionary to contain
BookResource
s instead, like this: