PDA

View Full Version : Are these two calculating functions different in terms of efficiency?

pml
03-13-2005, 04:40 PM
I just wonder if these functions are any different, in terms of efficiency. If so, in which way?

<script language="javascript" type="text/javascript">
var MyArray = new Array(2,5,17,8);

function1() {
var JoinedArray = MyArray.join("+");
total = eval(JoinedArray);
}

function2 {
var len = MyArray.length;
var total=0;
for(var i = 0; i < len ; i++)
{
total = total + myArray[i];
}
}

</script>

afru
03-13-2005, 05:32 PM
Sorry,

I changed my idea that 1st solution is the best and so I edited this post. In other words, 2nd soution is the best.

Checkout

Nice explanation.

Afru.

liorean
03-13-2005, 06:28 PM
eval is in all probability the biggest time consumer in that code. What it does is to basically start a new compiler. Try something like this instead:
Array.prototype.sum=function(){
var
i=this.length,
n=0;
while(i-->0)
n+=this[i];
}

total=MyArray.sum();The longer the array the more efficient eval gets, but the timing for the following script speaks it clear:
var
arr=[4,17,24,5,234,234,24,24,12,7456,12,5345,12,23,86,23,12,3,7,23,12,75,23,12,7,3,34,8,4,9,34,12],
n=1e4,
j,
t=0,
res,
i=n,
d=new Date,
timing=[];
do
eval(arr.join('+'));
while(0<--i)
timing.push(new Date - d);
i=n;
d=new Date;
do{
t=0
for(j=arr.length;j>0;j--)
t+=arr[j];
}while(0<--i)
timing.push(new Date - d);
i=n;
d=new Date;
do{
t=0
j=arr.length;
while(j-->0);
t+=arr[j];
}while(0<--i);
timing.push(new Date - d);
timing.join('\n');

// moz op iew
// -- -- --
// 1110 968 844
// 859 360 406
// 94 140 125