Last active
February 22, 2024 16:00
-
-
Save Lycolia/304bc9e825e821c2d582f3ef9f700817 to your computer and use it in GitHub Desktop.
Error handling benchmark at JavaScript
This file contains 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
const errorObject = (param) => { | |
if (param === true) { | |
return { | |
isError: false, | |
payload: 'TRUE', | |
}; | |
} else { | |
return { | |
isError: true, | |
payload: 'ERR', | |
}; | |
} | |
}; | |
const errorInstance = (param) => { | |
if (param === true) { | |
return 'TRUE'; | |
} else { | |
return new Error('ERR'); | |
} | |
}; | |
const throwErrorObject = (param) => { | |
if (param === true) { | |
return 'TRUE'; | |
} else { | |
throw { | |
type: '<==ERROR_OBJECT==>', | |
payload: 'ERR', | |
}; | |
} | |
}; | |
const throwErrorInstance = (param) => { | |
if (param === true) { | |
return 'TRUE'; | |
} else { | |
throw new Error('ERR'); | |
} | |
}; | |
const result = { | |
errorObject: 0, | |
errorInstance: 0, | |
throwErrorObject: 0, | |
throwErrorInstance: 0, | |
}; | |
const dt1 = +new Date(); | |
for (let i = 0; i < 1_000_000; i++) { | |
const ret = errorObject(i % 2 === 0); | |
if (ret.isError) { | |
console.log(ret.payload); | |
} | |
} | |
result.errorObject = +new Date() - dt1; | |
const dt2 = +new Date(); | |
for (let i = 0; i < 1_000_000; i++) { | |
const ret = errorInstance(i % 2 === 0); | |
if (ret instanceof Error) { | |
console.log(ret); | |
} | |
} | |
result.errorInstance = +new Date() - dt2; | |
const dt3 = +new Date(); | |
for (let i = 0; i < 1_000_000; i++) { | |
try { | |
const ret = throwErrorObject(i % 2 === 0); | |
} catch (err) { | |
console.log(err); | |
} | |
} | |
result.throwErrorObject = +new Date() - dt3; | |
const dt4 = +new Date(); | |
for (let i = 0; i < 1_000_000; i++) { | |
try { | |
const ret = throwErrorInstance(i % 2 === 0); | |
} catch (err) { | |
console.log(err); | |
} | |
} | |
result.throwErrorInstance = +new Date() - dt4; | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment