Skip to content

Instantly share code, notes, and snippets.

@pavelgolovan
Last active September 11, 2016 19:50
Show Gist options
  • Select an option

  • Save pavelgolovan/40ab80cad4c0cd5b4939d807834063b1 to your computer and use it in GitHub Desktop.

Select an option

Save pavelgolovan/40ab80cad4c0cd5b4939d807834063b1 to your computer and use it in GitHub Desktop.
try-catch vs try-catcher vs try-catch-iterate vs try-catcher-iterator wrapper
'use strict';
const ITERATIONS = 10000000;
const ERROR = new Error('Test error');
function tryCatcher(fn, ctx, args) {
try {
return fn.apply(ctx, args);
}
catch(err) {
return err;
}
}
function iterate() {
for (let i = ITERATIONS; i > 0; --i) {
(function () {})();
if (i === 1) {
throw ERROR;
}
}
}
let testFuncs = {
'arrow-func-try-catch': () => {
try {
for (let i = ITERATIONS; i > 0; --i) {
(function () {})();
if (i === 1) {
throw ERROR;
}
}
}
catch (error) {
console.log(error.message);
}
},
'arrow-func-try-catch-iterate': () => {
try {
iterate();
}
catch (error) {
console.log(error.message);
}
},
'arrow-func-try-cather': () => {
let res = tryCatcher(() => {
for (let i = ITERATIONS; i > 0; --i) {
(function () {})();
if (i === 1) {
throw ERROR;
}
}
});
if (res === ERROR) {
console.log(res.message);
}
},
'arrow-func-try-cather-iterate': () => {
let res = tryCatcher(iterate);
if (res === ERROR) {
console.log(res.message);
}
},
};
Object.keys(testFuncs).forEach(funcName => {
console.time(funcName);
testFuncs[funcName]();
console.timeEnd(funcName);
});
/*
=====================
Chrome Canary 55.0.2857.0 results
=====================
Test error
arrow-func-try-catch: 218ms
Test error
arrow-func-try-catch-iterate: 198ms
Test error
arrow-func-try-cather: 219ms
Test error
arrow-func-try-cather-iterate: 212ms
======================
Chrome 52.0.2743.116 results
======================
Test error
arrow-func-try-catch: 881.917ms
Test error
arrow-func-try-catch-iterate: 207.091ms
Test error
arrow-func-try-cather: 205.161ms
Test error
arrow-func-try-cather-iterate: 198.056ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment