Skip to content

Instantly share code, notes, and snippets.

@andrewbranch
Created December 19, 2014 03:20
Show Gist options
  • Save andrewbranch/381194a1f69361c29cb6 to your computer and use it in GitHub Desktop.
Save andrewbranch/381194a1f69361c29cb6 to your computer and use it in GitHub Desktop.
Explore the effect of Promises on JS speed and order of execution
var trash = [];
function computationallyIntensiveStuff() {
trash.push(Math.pow(Math.pow(Math.cos(Math.sin(Math.random())), Math.random()), Math.random() * 100000));
trash.filter(function (a) { return a > Math.random(); });
}
new Promise(function (resolve, reject) {
for (var i = 0; i < 1000; i++) {
computationallyIntensiveStuff();
}
resolve();
}).then(function () {
console.log('Promise done: ' + Date.now());
});
console.log('Next statement: ' + Date.now());
// Next statement: 1418958320178
// Promise done: 1418958320180 (2 ms later)
var trash = [];
function computationallyIntensiveStuff() {
trash.push(Math.pow(Math.pow(Math.cos(Math.sin(Math.random())), Math.random()), Math.random() * 100000));
trash.filter(function (a) { return a > Math.random(); });
}
setTimeout(function (resolve, reject) {
for (var i = 0; i < 1000; i++) {
computationallyIntensiveStuff();
}
console.log('Promise done: ' + Date.now());
}, 0);
console.log('Next statement: ' + Date.now());
// Next statement: 1418958579477
// Promise done: 1418958579509 (32 ms later)
var trash = [];
var startTime = Date.now();
var log = [];
function computationallyIntensiveStuff(whoCalled) {
trash.push(Math.pow(Math.pow(Math.cos(Math.sin(Math.random())), Math.random()), Math.random() * 100000));
trash.filter(function (a) { return a > Math.random(); });
log.push(whoCalled);
}
for (var i = 0; i < 1000; i++) {
computationallyIntensiveStuff('Drew');
}
for (var i = 0; i < 1000; i++) {
computationallyIntensiveStuff('Clay');
}
console.log(log);
console.log(Date.now() - startTime);
// [ 'Drew',
// ...998x
// 'Drew',
// 'Clay',
// ...998x
// 'Clay' ]
// 132 (ms)
var trash = [];
var startTime = Date.now();
var log = [];
function computationallyIntensiveStuff(whoCalled) {
trash.push(Math.pow(Math.pow(Math.cos(Math.sin(Math.random())), Math.random()), Math.random() * 100000));
trash.filter(function (a) { return a > Math.random(); });
log.push(whoCalled);
}
Promise.all([
new Promise(function (resolve, reject) {
for (var i = 0; i < 1000; i++) {
computationallyIntensiveStuff('Drew');
}
resolve();
}),
new Promise(function (resolve, reject) {
for (var i = 0; i < 1000; i++) {
computationallyIntensiveStuff('Clay');
}
resolve();
}),
]).then(function () {
console.log(log);
console.log(Date.now() - startTime);
});
// [ 'Drew',
// ...998x
// 'Drew',
// 'Clay',
// ...998x
// 'Clay' ]
// 138 (ms)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment