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 http://stackoverflow.com/questions/713286/enum-delegate-dictionary-collection-where-delegate-points-to-an-overloaded-metho
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