Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
mymymy
(version: 0)
Comparing performance of:
old vs new
Created:
5 years ago
by:
Guest
Jump to the latest result
Tests:
old
const Utils = class Self { static deepStringify (origData) { const getIsInstanceOfObject = function (val) { return typeof val === 'object' && val !== null } const parseForStringify = function (data) { if (Array.isArray(data)) { return data.map(el => getIsInstanceOfObject(el) ? parseForStringify(el) : el ) } if (getIsInstanceOfObject(data)) { return Object.getOwnPropertyNames(data) .reduce((acc, key) => Object.assign({}, acc, { [key]: getIsInstanceOfObject(data[key]) ? parseForStringify(data[key]) : data[key] }), {}) } return data } return JSON.stringify(parseForStringify(origData)) } static logError(/*{ args, msg, err }*/) { const params = arguments[0] === Object(arguments[0]) ? arguments[0] : {} const args = Array.isArray(params.args) ? params.args : [] const msg = typeof params.msg === 'string' ? params.msg : 'Internal error when processing some data' const err = params.err instanceof Error ? params.err : new Error('Unknown error') const stringifiedArgs = Self.deepStringify(args) //log in development console.log() console.error(` Function arguments:${stringifiedArgs}\n`, err) console.log() // for the logging service const commonProps = { arguments: JSON.parse(stringifiedArgs), date: new Date().toUTCString(), error: err } if (Self.isBrowser) { //TODO notify the user alert(msg) //logging service in production console.info(Self.deepStringify({ ...commonProps, localUrl: window.location.href, machineInfo: { browserInfo: window.navigator.userAgent, language: window.navigator.language, osType: window.navigator.platform } })) } if (Self.isNodeJS) { //logging service in production console.info(Self.deepStringify({ ...commonProps, localUrl: __filename, machineInfo: { cpuArch: process.arch, osType: process.platform, depVersions: process.versions } })) } } static catchFunc({ msg, defaultVal, innerFunc } = {}) { if (typeof innerFunc !== 'function') { Self.logError({ err: new Error(`Was not given a function - ${innerFunc}`) }) return defaultVal } if (innerFunc instanceof (async () => {}).constructor) { return async function(...args) { try { return await innerFunc.apply(this, args) } catch(err) { Self.logError({ err, args, msg }) return defaultVal } } } return function(...args) { try { return innerFunc.apply(this, args) } catch(err) { Self.logError({ err, args, msg }) return defaultVal } } } static createObject({ classesToInherit, classProps, instanceProps } = {}) { Self.finalizeClass.call(this.constructor, { classesToInherit, classProps }) Self.bindProps.call(this, { classesToInherit, instanceProps }) } static bindProps({ classesToInherit = [], instanceProps = {} } = {}) { if (!Object.isFrozen(this)) { //get the props from the inherited classes classesToInherit.map(constr => { //only the enumerable props Object.assign(this, new constr(instanceProps)) }) //set the remaining props Self.inheritProps.call(this, instanceProps) //bind the methods per object const targetProto = Object.getPrototypeOf(this) Object.getOwnPropertyNames(targetProto).map(key => { if (key !== 'constructor') { Object.defineProperty(this, key, { enumerable: false, value: targetProto[key] instanceof Function ? targetProto[key].bind(this) : targetProto[key] }) } }) //freeze the object Self.deepFreeze.call(this) } } static deepFreeze() { Object.getOwnPropertyNames(this).map(key => { if (typeof this[key] === 'object' && this[key] !== null) Self.deepFreeze.call(this[key]) }) Object.freeze(this) } static inheritProps(source) { if (!Object.isFrozen(this)) { Object.getOwnPropertyNames(source).map(key => { if (!this.hasOwnProperty(key)) { this[key] = source[key] } }) } } static errorHandleMethods(shouldHandleProto = true) { if (!Object.isFrozen(this)) { const descriptors = Object.getOwnPropertyDescriptors(this) Object.getOwnPropertyNames(this).map(key => { if (descriptors[key].writable && key !== 'constructor') { const msg = `Error inside method ${key}` this[key] = this[key] instanceof Function ? Self.catchFunc({ msg, innerFunc: this[key] }) : this[key] } }) if(shouldHandleProto) { Self.errorHandleMethods.call(this.prototype, false) } } } static finalizeClass({ classProps = {}, classesToInherit = [] } = {}) { if (!Object.isFrozen(this)) { // set class props Object.assign(this, classProps) // inherit methods from other classes classesToInherit.map(constr => { // class inherits static methods Self.inheritProps.call(this, constr) // class inherits prototype methods Self.inheritProps.call(this.prototype, constr.prototype) }) // error handle the inherited and the original methods Self.errorHandleMethods.call(this) // freeze the constructor Self.deepFreeze.call(this) } } } Utils.finalizeClass.call(Utils, { classProps: { isBrowser: typeof window !== 'undefined' && ({}).toString.call(window) === '[object Window]', isNodeJS: typeof global !== "undefined" && ({}).toString.call(global) === '[object global]' } }) const UncaughtErrorHandler = class Self { constructor({ server, port = 3000 } = {}) { const sockets = new Set() Self.startServer({ server, port, sockets }) Self.initUncaughtErrorHandling({ server, sockets }) } static startServer ({ server, port, sockets }) { if (Self.isNodeJS && server === Object(server)) { server.on('connection', socket => { console.log('Socket added') sockets.add(socket); socket.on('close', () => { console.log('Socket deleted') sockets.delete(socket) }) }) server.listen(port, err => { if (err) throw err console.log(`Server listening on ${port}`) }) } } static onUncaughtError (eventOrError, { server, sockets } = {}) { const msg = 'Fatal error! Please restart the application...' if (Self.isBrowser) { eventOrError.preventDefault() Self.logError({ msg, err: eventOrError.error || eventOrError.reason }) // prevent user from interacting with the page window.document.body.style['pointer-events'] = 'none' } if (Self.isNodeJS) { if (server) server.close() if (sockets) sockets.forEach(socket => { socket.destroy() }) Self.logError({ msg, err: eventOrError instanceof Error ? eventOrError : new Error('Process interrupted') }) // shutdown the node process setTimeout(() => process.exit(1), 1000).unref() } } static initUncaughtErrorHandling({ server, sockets } = {}) { const errorFunc = function (err) { Self.onUncaughtError.call(this, err, { server, sockets }) } if (Self.isBrowser) { window.addEventListener('error', errorFunc, true) window.addEventListener('unhandledrejection', errorFunc, true) } if (Self.isNodeJS) { process.on('uncaughtException', errorFunc) process.on('unhandledRejection', errorFunc) process.on('SIGTERM', errorFunc) process.on('SIGINT', errorFunc) } } } Utils.finalizeClass.call(UncaughtErrorHandler, { classesToInherit: [ Utils ] }) /************************/ /******* EXAMPLES *******/ /************************/ // BADLY written class class Height { constructor(args = {}) { this.height = args.height + 1000 } getHeight() { return `Height: ${this.height}` } throwErrorForHeight() { throw new Error('Error from instance of Height method') } } // BADLY written class class Weight { constructor(args = {}) { this.weight = args.weight + ' kg' } getWeight() { return `Weight: ${this.weight}` } static throwErrorForWeight() { throw new Error('Error from Weight method') } } // WELL written class const Person = class Self { constructor(args = {}) { Utils.createObject.call(this, { classesToInherit: [Height, Weight], classProps: { species: 'humans' }, instanceProps: { name: args.name || 'John', age: args.age || 20, weight: args.weight || 60, height: args.height || 160 } }) } // Uncomment to replace the inherited one getHeight() { return 'Correct height' } // combines native with inherited methods greet() { console.log(`Hello, ${this.name}. ${this.getWeight()}, ${this.getHeight()}`) } // calculates the method name first ['get' + 'Info']() { return `Name: ${this.name}, age: ${this.age}` } throwErrorForInstance() { throw new Error('Error shows up in instance methods') } // class method static internalMethod() { return 'Hello from inside the class' } static throwErrorForPerson() { throw new Error('Error shows up in Person methods') } // can also use async, * generator // which can also be static } const mark = new Person({ name: 'Mark', weight: 70 }) // copy mark props and replace some of them const fatMark = new Person({ ...mark, weight: 110 })
new
const GenericUtils = class Self { static deepFreeze(obj) { Object.getOwnPropertyNames(obj).map(key => { if (typeof obj[key] === 'object' && obj[key] !== null) Self.deepFreeze(obj[key]) }) Object.freeze(obj) } static inheritProps(obj, source) { if (!Object.isFrozen(obj)) { Object.getOwnPropertyNames(source).map(key => { if (!obj.hasOwnProperty(key)) { obj[key] = source[key] } }) } } static setClassProps(obj, { props = {}, inherited = [] } = {}) { if (!Object.isFrozen(obj)) { // set class props Object.assign(obj, props) // inherit methods from other classes inherited.map(constr => { // class inherits static methods Self.inheritProps(obj, constr) // class inherits prototype methods Self.inheritProps(obj.prototype, constr.prototype) }) // give access to inherited classes obj.inherited = inherited } } static deepStringify (origData) { const getIsInstanceOfObject = function (val) { return typeof val === 'object' && val !== null } const parseForStringify = function (data) { if (Array.isArray(data)) { return data.map(el => getIsInstanceOfObject(el) ? parseForStringify(el) : el ) } if (getIsInstanceOfObject(data)) { return Object.getOwnPropertyNames(data) .reduce((acc, key) => Object.assign({}, acc, { [key]: getIsInstanceOfObject(data[key]) ? parseForStringify(data[key]) : data[key] }), {}) } return data } return JSON.stringify(parseForStringify(origData)) } static logError(/*{ args, msg, err }*/) { const params = arguments[0] === Object(arguments[0]) ? arguments[0] : {} const args = Array.isArray(params.args) ? params.args : [] const msg = typeof params.msg === 'string' ? params.msg : 'Internal error when processing some data' const err = params.err instanceof Error ? params.err : new Error('Unknown error') const stringifiedArgs = Self.deepStringify(args) //log in development console.log() console.error(` Function arguments:${stringifiedArgs}\n`, err) console.log() // for the logging service const commonProps = { arguments: JSON.parse(stringifiedArgs), date: new Date().toUTCString(), error: err } if (Self.isBrowser) { //TODO notify the user alert(msg) //logging service in production console.info(Self.deepStringify({ ...commonProps, localUrl: window.location.href, machineInfo: { browserInfo: window.navigator.userAgent, language: window.navigator.language, osType: window.navigator.platform } })) } if (Self.isNodeJS) { //logging service in production console.info(Self.deepStringify({ ...commonProps, localUrl: __filename, machineInfo: { cpuArch: process.arch, osType: process.platform, depVersions: process.versions } })) } } static catchFunc({ msg, defaultVal, innerFunc } = {}) { if (typeof innerFunc !== 'function') { Self.logError({ err: new Error(`Was not given a function - ${innerFunc}`) }) return defaultVal } if (innerFunc instanceof (async () => {}).constructor) { return async function(...args) { try { return await innerFunc.apply(this, args) } catch(err) { Self.logError({ err, args, msg }) return defaultVal } } } return function(...args) { try { return innerFunc.apply(this, args) } catch(err) { Self.logError({ err, args, msg }) return defaultVal } } } static errorHandleMethods(obj, shouldHandleProto = true) { if (!Object.isFrozen(obj)) { const descriptors = Object.getOwnPropertyDescriptors(obj) Object.getOwnPropertyNames(obj).map(key => { if (descriptors[key].writable && key !== 'constructor') { const msg = `Error inside method ${key}` obj[key] = obj[key] instanceof Function ? Self.catchFunc({ msg, innerFunc: obj[key] }) : obj[key] } }) if(shouldHandleProto) { Self.errorHandleMethods(obj.prototype, false) } } } } GenericUtils.setClassProps(GenericUtils, { props: { isBrowser: typeof window !== 'undefined' && ({}).toString.call(window) === '[object Window]', isNodeJS: typeof global !== "undefined" && ({}).toString.call(global) === '[object global]' } }) GenericUtils.errorHandleMethods(GenericUtils, true) GenericUtils.deepFreeze(GenericUtils) const PureClass = class Self { constructor(instanceProps = {}) { if (!Object.isFrozen(this)) { //get the props from the inherited classes const inherited = this.constructor.inherited || [] inherited.map(constr => { //only the enumerable props Object.assign(this, new constr(instanceProps)) }) //set the remaining props GenericUtils.inheritProps(this, instanceProps) const targetProto = Object.getPrototypeOf(this) //bind the methods per object Object.getOwnPropertyNames(targetProto).map(key => { if (key !== 'constructor') { Object.defineProperty(this, key, { enumerable: false, value: targetProto[key] instanceof Function ? targetProto[key].bind(this) : targetProto[key] }) } }) //seal the object shallowly, if you want deepFreeze, //implement it after creation - GenericUtils.deepFreeze(objName) Object.seal(this) } } static finalizeClass({ props = {}, inherited = [] } = {}) { if (!Object.isFrozen(this)) { GenericUtils.setClassProps(this, { props, inherited }) // error handle the inherited and the original methods GenericUtils.errorHandleMethods(this) // freeze the whole class GenericUtils.deepFreeze(this) } } } GenericUtils.errorHandleMethods(PureClass, true) GenericUtils.deepFreeze(PureClass) /************************/ /******* EXAMPLES *******/ /************************/ // BADLY written class class Height { constructor(args = {}) { this.height = args.height + 1000 } getHeight() { return `Height: ${this.height}` } throwErrorForHeight() { throw new Error('Error from instance of Height method') } } // BADLY written class class Weight { constructor(args = {}) { this.weight = args.weight + ' kg' } getWeight() { return `Weight: ${this.weight}` } static throwErrorForWeight() { throw new Error('Error from Weight method') } } // WELL written class const Person = class Self extends PureClass { constructor(args = {}) { super({ name: args.name || 'John', age: args.age || 20, weight: args.weight || 60, height: args.height || 160 }) } // Uncomment to replace the inherited one getHeight() { return 'Correct height' } // combines native with inherited methods greet() { console.log(`Hello, ${this.name}. ${this.getWeight()}, ${this.getHeight()}`) } // calculates the method name first ['get' + 'Info']() { return `Name: ${this.name}, age: ${this.age}` } throwErrorForInstance() { throw new Error('Error shows up in instance methods') } // class method static internalMethod() { return 'Hello from inside the class' } static throwErrorForPerson() { throw new Error('Error shows up in Person methods') } // can also use async, * generator // which can also be static } Person.finalizeClass({ inherited: [Height, Weight], props: { species: 'humans' } }) const mark = new Person({ name: 'Mark', weight: 70 }) // copy mark props and replace some of them const fatMark = new Person({ ...mark, weight: 110 }) const UncaughtErrorHandler = class Self extends PureClass { constructor({ server, port = 3000 } = {}) { super({ sockets: new Set(), server, port }) } static onUncaughtError (eventOrError) { const msg = 'Fatal error! Please restart the application...' if (Self.isBrowser) { eventOrError.preventDefault() Self.logError({ msg, err: eventOrError.error || eventOrError.reason }) // prevent user from interacting with the page window.document.body.style['pointer-events'] = 'none' } if (Self.isNodeJS) { if (this.server !== undefined) this.server.close() if (this.sockets !== undefined) this.sockets.forEach(socket => { socket.destroy() }) Self.logError({ msg, err: eventOrError instanceof Error ? eventOrError : new Error('Process interrupted') }) // shutdown the node process setTimeout(() => process.exit(1), 1000).unref() } } startServer () { if (Self.isNodeJS && this.server !== undefined) { this.server.on('connection', socket => { console.log('Socket added') this.sockets.add(socket); socket.on('close', () => { console.log('Socket deleted') this.sockets.delete(socket) }) }) this.server.listen(this.port, err => { if (err) throw err console.log(`Server listening on ${this.port}`) }) } } initUncaughtErrorHandling() { const errorFunc = Self.onUncaughtError.bind(this) if (Self.isBrowser) { window.addEventListener('error', errorFunc, true) window.addEventListener('unhandledrejection', errorFunc, true) } if (Self.isNodeJS) { this.startServer() process.on('uncaughtException', errorFunc) process.on('unhandledRejection', errorFunc) process.on('SIGTERM', errorFunc) process.on('SIGINT', errorFunc) } } } UncaughtErrorHandler.finalizeClass({ inherited: [GenericUtils] })
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
old
new
Fastest:
N/A
Slowest:
N/A
Latest run results:
No previous run results
This benchmark does not have any results yet. Be the first one
to run it!
Autogenerated LLM Summary
(model
llama3.2:3b
, generated one year ago):
It looks like you're providing an excerpt from a JavaScript codebase, specifically a class definition and some benchmarking data. Without knowing the specific question or task you'd like me to help with, I'll take a stab in the dark: Are you looking for something like: 1. Code review: would you like me to review the provided class definition and provide feedback on its organization, syntax, and overall structure? 2. Debugging: are there any errors or issues in the code that you'd like me to help identify and potentially fix? 3. Performance optimization: based on the benchmarking data, are there any performance-related questions or improvements you'd like me to help with? Please let me know if I'm on the right track or if you have something else in mind!
Related benchmarks:
Lodash Array isEqual vs Native
IndexOf vs Includes vs hash vs set
Hash vs insert
test jsss
Reflect.has vs Direct Check
Comments
Confirm delete:
Do you really want to delete benchmark?