Created
October 23, 2024 12:55
-
-
Save jkup/7cc6eb0b294e17a3b6dab2b4c0200fe9 to your computer and use it in GitHub Desktop.
InternedStrings
This file contains hidden or 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
// Class | |
class InternedString { | |
static internedStrings = new Map(); | |
static nextId = 0; | |
constructor(value) { | |
this.id = InternedString.nextId++; | |
this.value = value; | |
} | |
static intern(value) { | |
if (InternedString.internedStrings.has(value)) { | |
return InternedString.internedStrings.get(value); | |
} | |
const internedString = new InternedString(value); | |
InternedString.internedStrings.set(value, internedString); | |
return internedString; | |
} | |
equals(other) { | |
return other === this.value; | |
} | |
copy() { | |
return this.value; | |
} | |
toString() { | |
return this.value; | |
} | |
} |
This file contains hidden or 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 numIterations = 100000; | |
const str = 'hello'; | |
function benchmarkInternedString() { | |
const internedStr = InternedString.intern(str); | |
let start = Date.now(); | |
for (let i = 0; i < numIterations; i++) { | |
internedStr.equals(str); | |
} | |
console.log(`InternedString equality: ${Date.now() - start}ms`); | |
} | |
function benchmarkInternedStringCopy() { | |
const internedStr = InternedString.intern(str); | |
let start = Date.now(); | |
for (let i = 0; i < numIterations; i++) { | |
internedStr.copy(); | |
} | |
console.log(`InternedString copy: ${Date.now() - start}ms`); | |
} | |
benchmarkInternedString(); | |
benchmarkInternedStringCopy(); |
This file contains hidden or 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 numIterations = 100000; | |
const str = 'hello'; | |
function benchmarkNativeString() { | |
let start = Date.now(); | |
for (let i = 0; i < numIterations; i++) { | |
str === str; | |
} | |
console.log(`NativeString equality: ${Date.now() - start}ms`); | |
} | |
function benchmarkNativeStringCopy() { | |
let start = Date.now(); | |
for (let i = 0; i < numIterations; i++) { | |
str + ''; | |
} | |
console.log(`NativeString copy: ${Date.now() - start}ms`); | |
} | |
benchmarkNativeString(); | |
benchmarkNativeStringCopy(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment