Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Are these two calculating functions different in terms of efficiency?

1. ## Are these two calculating functions different in terms of efficiency?

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>

• 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
http://www.webdeveloper.com/forum/sh...027#post333027

Nice explanation.

Afru.

• 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:
Code:
```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:
Code:
```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```

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•