WF4 Performance Tip–Cache Activities

When you create a new WorkflowConsole application you will see a line of code like this

    1: WorkflowInvoker.Invoke(new Workflow1());

Looks innocent enough right? If you were only going to invoke this activity once this is not a problem.  But what if you were going to invoke this activity thousands of times? Suppose you wanted to use the activity in a WCF Service? What would the performance characteristic be?

You need to understand what happens when you create and invoke an activity. There is a great deal of one-time overhead which you could avoid by making one simple change. Here it is…

    1: private static Activity cachedActivity = new Workflow1();
    3: private static void CacheInvoke()
    4: {
    5:     WorkflowInvoker.Invoke(cachedActivity);
    6: }

How big of a difference does this make? Plenty… Here is a test app that uses each method 100 times.


How about 4ms vs 504ms – is that fast enough for you?

Want to know what is really going on under the covers here?  Watch this.