DLR and Performance

Michael Schwarz on Thursday, May 31, 2007

The idea was to put all JavaScript libraries into the DLR of Silverlight to get better performance, but a first tests failed or is compared to JavaScript directly in the Web browser very slow.

To test this I wrote a very simple demo:

var s = ""; var d1 = <span class="kwrd">new</span> Date(); 

<span class="kwrd">for</span>(var i=0; i&lt;1000; i++) { s += <span class="str">"abcdefghijklmnopqrstuvwxyz"</span>; }

var d2 = <span class="kwrd">new</span> Date(); var v = d2.getTime() - d1.getTime();

text1.Text += v + <span class="str">"msec "</span>; </pre>

This function I executed twice in JavaScript and managed JScript (DLR) and got following results:

IE: 9msec with JavaScript and in DLR 62msec, 2nd time 19msec

Firefox: 1msec with JavaScript and in DLR 60msec, 2nd time 17msec

What I understand is the initial invoke that needs longer than the second one. But what I expected was that the compiled version will run the second time faster then the JavaScript version.

I got a very detailed answer from Jim Hugunin [1], in short:

"This first alpha1 release of javascript on the dlr was focused on getting a correct implementation of the js language, driving features needed for js into the dlr, and being able to explore the programming model for js on silverlight.  We didn't have time to both do this and to look at performance.  This means that performance of this alpha1 release is rather disappointing – but based on our experiences with IronPython we expect to see this performance get dramatically better over the next few months."

He will post the full detailed answer next on his blog at http://blogs.msdn.com/hugunin [2], add his feed to your RSS reader...

JavaScript and System.Text.StringBuilder

The next idea was to use the StringBuilder instead of a simple string, but I couldn't increase the performance for this test, it tooks the same as simple string concatenation.

<pre class="csharpcode">var sb = <span class="kwrd">new</span> StringBuilder();

var d = <span class="kwrd">new</span> Date(); <span class="kwrd">for</span>(var i=0; i&lt;1000; i++) { sb.Append(<span class="str">"abcdefghijklmnopqrstuvwxyz"</span>); } text1.Text = (<span class="kwrd">new</span> Date().getTime() - d.getTime());</pre>

If you currently need to build large strings (i.e. to render a XAML or HTML string) you should use it like you did it in JavaScript before: with Arrays.