Created
July 23, 2014 21:29
-
-
Save mraleph/99579ede7c52d1018f2d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function B1() { | |
/* Benchmark.prototype.setup goes here {{{ */ | |
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], | |
seed_data = 3, | |
result = 0; | |
/* }}} */ | |
var start = new Date; | |
while (...) { /* do N iterations of test body */ | |
/* body of the case goes here {{{ */ | |
for (var i = 0; i < arr1.length; i++) { | |
result += (seed_data * i); | |
} | |
/* }}} */ | |
} | |
var end = new Date; | |
/* N / (end - start) gives ops per ms result */ | |
} | |
function B2() { | |
/* Benchmark.prototype.setup goes here {{{ */ | |
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], | |
seed_data = 3, | |
result = 0; | |
/* }}} */ | |
var start = new Date; | |
while (...) { /* do N iterations of test body */ | |
/* body of the case goes here {{{ */ | |
var l = arr1.length; | |
for (var i = 0; i < l; i++) { | |
result += (seed_data * i); | |
} | |
/* }}} */ | |
} | |
var end = new Date; | |
/* N / (end - start) gives ops per ms result */ | |
} | |
function B3() { | |
/* Benchmark.prototype.setup goes here {{{ */ | |
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], | |
seed_data = 3, | |
result = 0; | |
/* }}} */ | |
var start = new Date; | |
while (...) { /* do N iterations of test body */ | |
/* body of the case goes here {{{ */ | |
var arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
for (var i = 0; i < arr2.length; i++) { | |
result += (seed_data * i); | |
if (i === 4) { | |
arr2.push(10) | |
} | |
} | |
/* }}} */ | |
} | |
var end = new Date; | |
/* N / (end - start) gives ops per ms result */ | |
} | |
Awesome! Thanks for help me to find the right case.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Questions to ask yourself here: does operation that we are measuring in
B3
perform the same amount of work as inB1
andB2
?The key to the answer here is to perceive the whole case as an operation. Then the answer is obvious: no, in
B3
we allocate one additional array per iteration and we alter the array.You can try something more like this http://jsperf.com/cache-length-for/4 instead where you try to balance the amount of work you do in all cases (it should be equal).