Skip to content

Instantly share code, notes, and snippets.

@sidorares
Last active January 31, 2024 18:18
Show Gist options
  • Save sidorares/e735b99b68c33871e74f789e1fa6f5e3 to your computer and use it in GitHub Desktop.
Save sidorares/e735b99b68c33871e74f789e1fa6f5e3 to your computer and use it in GitHub Desktop.
key sanitization benchmark
'use strict';
// 10 variables
const key1 = 'Basic local performance checking for 15,000 large unique keys generated by using:';
const key2 = 'age';
const key3 = 'addres - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10';
const key4 = 'hobby';
const key5 = 'phone/phone_number';
const key6 = 'Basic local performance checking for 15,000 | " escape from reality" | large unique keys generated by using:';
const key7 = 'job';
const key8 = 'some_long_variable/name/with/many/segments';
function sanitizeKey(value, delimiter = ':') {
const str = String(value);
if (str === 'undefined') return '_';
let res = '';
for (let i = 0, len = str.length; i < len; i++) {
if (str[i] === '_') {
// Ensuring that `some_key` is diffenret from `some{delimiter}key`
res += '__';
} else if (str[i] === delimiter) {
res += '_';
} else {
res += str[i];
}
}
return res;
}
function generateCompoundKey1() {
return (
key1 +
'_' +
key2 +
'_' +
Boolean(1) +
'/' +
//new Date() +
//'_' +
Boolean(2) +
key3 +
'_' +
key4 +
'_' +
key5 +
'_' +
key6 +
'_' +
key7 +
'_' +
key8
);
}
// same, but using sanitizeKey
function generateCompoundKey2() {
return (
sanitizeKey(key1, '/') +
'_' +
sanitizeKey(key2, '/') +
'_' +
Boolean(1) +
'/' +
//new Date() +
//'_' +
Boolean(2) +
sanitizeKey(key3, '/') +
'_' +
sanitizeKey(key4, '/') +
'_' +
sanitizeKey(key5, '/') +
'_' +
sanitizeKey(key6, '/') +
'_' +
sanitizeKey(key7, '/') +
'_' +
sanitizeKey(key8, '/')
);
}
// same, but using JSON.stringify
function generateCompoundKey3() {
return JSON.stringify([
key1,
key2,
Boolean(1),
//new Date(),
Boolean(2),
key3,
key4,
key5,
key6,
key7,
key8,
]);
}
function benchmark(keySerializer) {
// benchmark it
const start1 = new Date();
let length = 0;
for (let i = 0; i < 1000000; i++) {
length = keySerializer().length;
}
const end1 = new Date();
console.log(
`Time taken for ${keySerializer.name}: ${
end1 - start1
}. Key length: ${length}`
);
}
console.log(generateCompoundKey1());
console.log(generateCompoundKey2());
console.log(generateCompoundKey3());
// benchmark 20 times
for (let i = 0; i < 5; i++) {
benchmark(generateCompoundKey1);
}
for (let i = 0; i < 5; i++) {
benchmark(generateCompoundKey2);
}
// benchmark 20 times
for (let i = 0; i < 5; i++) {
benchmark(generateCompoundKey3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment