Silverlight managed code vs. JavaScript

I finally had a chance to play with Silverlight today. The managed code capabilities is very interesting, so I set out to create a simple performance tester.

I created two basic managed methods in Silverlight. One that multiplies a number and returns a result, and another that does the same thing a specified number of times:

[Scriptable]
public double Multiply(double a, double b)
{
   return a * b;
}
[Scriptable]
public double MultiplyLoop(double a, double b, int count)
{
   double result = 0;
   for (int i = 0; i < count; i++)
      result = a * b;
   return result;
}

This gives me 3 test-cases to compare:

  • Multiply two numbers n times in pure javascript.
  • Multiply two numbers n times, by calling Multiply(a,b) from JavaScript into managed code n times
  • Multiply two numbers n times, by calling MultiplyLoop(a,b,n) from Javascript into managed code one time.

What I found was:

  • JavaScript is fairly slow to do this (345 ms for 10 millions calculations).
  • Calling a managed method millions of times is VERY slow (IE asked me several times whether I wanted to abort it before it finished)
  • Calling a managed method once and do the looping in managed code is VERY fast (0-2 ms).

The conclusion here would be that you shouldn't have methods in managed code that you call a lot from javascript unless they are process-intensive. There seems to be a big overhead in calling into managed code, but as soon as you are in the managed process, its blazing fast.

You can download my test sample here: SilverlightProject1.zip (18.35 KB)  (requires Orcas beta 1 and Silverlight add-on)

Now on to move all my existing .NET libraries into a Silverlight app... :-)

Add comment