There are two alternatives I have for executing a piece of code. The code basically resets all the values in three arrays. Two of them are int arrays and one is boolean.
Choice 1
for (i = 0; i < array1.length; i++)
array1[i] = 0;
for (i = 0; i < array2.length; i++)
array2[i] = 0;
for (i = 0; i < array3.length; i++)
array3[i] = false;
Choice 2
int limit = <assign the greatest of the array lengths>
for (i = 0; i < limit; i++)
{
if (i < array1.length)
array1[i] = 0;
if (i < array2.length)
array2[i] = 0;
if (i < array3.length)
array3[i] = false;
}
Which of these would be faster? Given that the arrays can have varying lengths and have no relationship with each other.
There is a real good discussion here. The answer listed first explains quiet well what arrays actually mean in javascript. For those interested to check it out!
-
5I strongly doubt that the difference will be substantial. Don't waste your time with such mikro-optimizations.Niko– Niko2012年08月23日 10:07:20 +00:00Commented Aug 23, 2012 at 10:07
-
You should measure it :)Asciiom– Asciiom2012年08月23日 10:07:30 +00:00Commented Aug 23, 2012 at 10:07
-
@Niko: I am trying to learn how best to program. Hence started off with a small query like this. Dietrich has already given me good info!TheSilverBullet– TheSilverBullet2012年08月23日 10:10:55 +00:00Commented Aug 23, 2012 at 10:10
-
+1 for testing me against root of evilhuseyin tugrul buyukisik– huseyin tugrul buyukisik2012年08月23日 10:15:15 +00:00Commented Aug 23, 2012 at 10:15
-
1There is a thorough discussion of array initialization performance here : stackoverflow.com/questions/1295584/…StuartLC– StuartLC2012年08月23日 10:15:27 +00:00Commented Aug 23, 2012 at 10:15
2 Answers 2
This version is almost certainly going to be faster. It is also easier to read and shorter, which are both much more important attributes than speed (99+% of the time).
for (i = 0; i < array1.length; i++)
array1[i] = 0;
for (i = 0; i < array2.length; i++)
array2[i] = 0;
for (i = 0; i < array3.length; i++)
array3[i] = false;
In general, it is faster to access data that is close in memory to data that you accessed recently.
This version also does not suffer from additional branching you would get in the second version.
A sufficiently advanced compiler would transform the second version into the first.
Benchmarking: Micro-benchmarks are 100% useless without profiling your entire program first. Since I don't think the performance measurements are useful, I am not providing them.
2 Comments
function reset_array(array, value) {
var len = array.length;
array.length = 0;
while (len--) array.push(value);
}
reset_array(array1, 0);
reset_array(array2, 0);
reset_array(array3, false);
4 Comments
Explore related questions
See similar questions with these tags.