Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
string type convertion benchmark
const emptyStringMethod = value => value + '';
const stringMethod = value => String(value);
const templateMethod = value => `${value}`;
const toStringMethod = value => value.toString();
const concatMethod = value => ''.concat(value);
const combinedMethod = value => {
if (value === null) {
return 'null';
}
if (value === undefined) {
return 'undefined';
}
if (typeof value === 'string') {
return value;
}
if (typeof value === 'symbol') {
return String(value);
}
if (typeof value === 'object') {
return value.toString();
}
return `${value}`;
}
const noopMethod = value => value;
combinedMethod.toString = () => 'combinedMethod';
const methods = {
emptyStringMethod,
stringMethod,
templateMethod,
toStringMethod,
concatMethod,
combinedMethod,
noopMethod,
};
const undefinedValue = undefined;
const nullValue = null;
const numberValue = 233;
const bigintValue = 233333n;
const stringValue = 'string';
const booleanValue = true;
const objectValue = {};
const functionValue = () => {};
const arrayValue = ['a', 'r', 'r', 'a', 'y'];
const dateValue = new Date();
const mapValue = new Map();
const setValue = new Set();
const symbolValue = Symbol();
const values = {
undefinedValue,
nullValue,
numberValue,
bigintValue,
stringValue,
booleanValue,
objectValue,
functionValue,
arrayValue,
dateValue,
mapValue,
setValue,
symbolValue,
};
console.log('================= Compatibility =================');
console.log('');
Object.values(methods).forEach(method => {
console.log(`// ${method.toString()}`);
Object.entries(values).forEach(([valueName, value]) => {
try {
console.log(valueName, '//', method(value));
} catch (e) {
console.log(valueName, '//', e.name, ':', e.message);
}
});
console.log('');
});
console.log('================= Performance =================');
console.log('');
Object.entries(values).forEach(([valueName, value]) => {
console.log(`// ${valueName}`);
Object.values(methods).forEach(method => {
try {
console.time(`${method.toString()} // ${valueName}`);
for (let i = 0; i < 10000000; i++) {
method(value)
}
console.timeEnd(`${method.toString()} // ${valueName}`);
} catch (e) {
console.log(method.toString(), '//', e.name, ':', e.message);
}
});
console.log('');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.