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.

Comments (3)

  1. Moiz says:

    Testing – wrote a comment,not sure you got it.

  2. Mas says:

    Would this CacheInvoke() method be thread-safe? MSDN does not indicate that Activity instances are thread-safe.

  3. Ron Jacobs says:

    Yes – Remember that cachedActivity is a workflow definition (like a Type in the CLR).  And in fact the CLR caches Types for the same reason.  When you invoke it again a new instance of the activity is created and this is thread safe.