Wednesday, February 6, 2008

C# vs VBScript

After writing another VBScript script for our System I began wondering what's the difference in performance between a script and a compiled program.
So I began by writing a nice VBScript that does heavy calculation (I used the calculation of n! for n=1 to 100) Using a normal computer it takes almost no time, well, repeat it for 10000 times... The script I wrote is:
Option Explicit

Call Main()

Sub Main()
Dim StartingTime
Dim EndingTime

StartingTime = Now()
Call DoHardWork(100)
EndingTime = Now()
WScript.Echo "Started at: " & StartingTime
WScript.Echo "Finished at: " & EndingTime
WScript.Echo "Total time: " & DateDiff("s",StartingTime,EndingTime) & " sec"
End Sub

Sub DoHardWork(MaxI)
Dim i
Dim j

For j = 1 To 10000
For i = 1 To MaxI
Call RecursiveCalc(i)
Next
Next
End Sub

Function RecursiveCalc(CurNum)
If curnum = 1 Then
RecursiveCalc = 1
Else
RecursiveCalc = CurNum * RecursiveCalc (CurNum - 1)
End If
End Function


Dumb, does the job using no cache and other enhancements. The script took 107s on my computer. I felt this is a good benchmark, I'll write a simple C# program and run it. How fast can it be? The C# program I wrote is almost an exact copy of the VBS:
using System;
using System.Collections.Generic;
using System.Text;

namespace TimeCheck
{
class Program
{
static void Main(string[] args)
{
DateTime StartingTime = DateTime.Now;
DoHardWork(100);
DateTime EndingTime = DateTime.Now;
Console.WriteLine("Started at: " + StartingTime.ToString());
Console.WriteLine("Finished at: " + EndingTime.ToString());
Console.WriteLine("Total time: " + EndingTime.Subtract(StartingTime).ToString());
}

static void DoHardWork(int MaxI)
{
for (int j = 1; j < 10000; j++)
{
for (int i = 1; i < MaxI; i++)
{
RecursiveCalc(i);
}
}
}

static long RecursiveCalc(int CurNum)
{
if (CurNum == 1)
{
return 1;
}
else
{
return CurNum * RecursiveCalc(CurNum - 1);
}
}
}
}


The results are: 1.57464s for the "Debug" compilation.
The "Release" took 1.023516s. If anyone needs a reminding of the difference between programs and scripts.

P.S. if anyone wants to do the same test in another language, please send me the results, I'd like to add more to the results chart in the future.

No comments: