Skip to content

Instantly share code, notes, and snippets.

@mindoftea
Last active March 14, 2016 19:05
Show Gist options
  • Save mindoftea/95f1cc708be0446021cf to your computer and use it in GitHub Desktop.
Save mindoftea/95f1cc708be0446021cf to your computer and use it in GitHub Desktop.
const arraySize = 1e3;
const trialSize = 1e6;
const a = [];
let i = arraySize;
while (i--) {
a[i] = i;
}
const t = [];
const x = a.slice();
t[0] = Date.now();
i = trialSize;
while (i--) {
// Test case:
for (let n = 0; n < x.length; n++) {
x[n]++;
}
}
t[0] = Date.now() - t[0];
print("Forward for loop: " + t[0]);
const y = a.slice();
t[1] = Date.now();
i = trialSize;
while (i--) {
// Test case:
let n = 0;
while (n++ < y.length) {
y[n - 1]++;
}
}
t[1] = Date.now() - t[1];
print("Forward while loop:", t[1]);
const z = a.slice();
t[2] = Date.now();
i = trialSize;
while (i--) {
// Test case:
for (let n = z.length - 1; n >= 0; n--) {
z[n]++;
}
}
t[2] = Date.now() - t[2];
print("Backward for loop: " + t[2]);
const w = a.slice();
t[3] = Date.now();
i = trialSize;
while (i--) {
// Test case:
let n = w.length;
while (n--) {
w[n]++;
}
}
t[3] = Date.now() - t[3];
print("Backward while loop:", t[3]);
@mindoftea
Copy link
Author

Results when run with v8 standalone:

Forward for loop: 2258
Forward while loop: 1300
Backward for loop: 2272
Backward while loop: 1149

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment