Monday, January 12, 2009

Reusing Import Symbols to Avoid Performance Hits

Philipp Sumi has been looking at performance optimizations when using IronPython hosted from C#.
Lets do an artificial sample: The snippet below just increments a variable by one. As expected, it executes blazingly fast - after compilation, it executes a few thousand times without getting over a single millisecond:

value = value + 1

Now look at the following example:

import clr
clr.AddReference('System.Xml')
from System.Xml import *
value = value + 1

Basically, this snippet performs the same logic (incrementing the ‘value’ variable), but it contains an import for the System.Xml namespace. It’s not necessary, but it still needs to be compiled. Executing this (compiled!) script 4000 times takes over 5 seconds!
From a hosting point of view, the extra time is spent populating the namespace (the ScriptScope) in which the code is executed. Philipp shows how to reuse imports by creating new scopes from a pre-populated SymbolDictionary.

2 comments:

  1. Do you really need the ``import *`` call? If you simply import the module, which best practice says you (typically) should do, what do the numbers come out to?

    ReplyDelete
  2. Hey Brett - you're probably better off commenting on the original posting.

    As this is an embedding situation I *imagine* he really does want to make all those names available to user code that is executed. Whether that is the best way to expose an API to the user is another question. :-)

    ReplyDelete

Note: only a member of this blog may post a comment.