Permalink
Fetching contributors…
Cannot retrieve contributors at this time
56 lines (50 sloc) 1.81 KB
'use strict';
// Compilers such as V8 use string interning to make string comparison very fast and efficient,
// as efficient as comparing two references to the same object.
//
//
// V8 does its best to intern strings automatically where it can, for instance:
// ```js
// var greeting = "hello world";
// ```
// With this, comparison will be very fast:
// ```js
// if (greeting === "hello world") {}
// ```
// However, there are several cases where V8 cannot intern the string, and instead
// must resort to byte-wise comparison. This can be signficantly slower for long strings.
// The most common example is string concatenation:
// ```js
// function subject () { return "world"; };
// var greeting = "hello " + subject();
// ```
// In this case, V8 cannot intern the string. So this comparison is *much* slower:
// ```js
// if (greeting === "hello world") {}
// ```
// At the moment, the fastest, safe way of interning a string is to
// use it as a key in an object, and then use that key.
//
// Note: This technique comes courtesy of Petka Antonov - http://jsperf.com/istrn/11
//
// We create a container object in hash mode.
// Most strings being interned will not be valid fast property names,
// so we ensure hash mode now to avoid transitioning the object mode at runtime.
var container = {'- ': true};
delete container['- '];
/**
* Intern a string to make comparisons faster.
*
* > Note: This is a relatively expensive operation, you
* shouldn't usually do the actual interning at runtime, instead
* use this at compile time to make future work faster.
*
* @param {String} string The string to intern.
* @return {String} The interned string.
*/
module.exports = function fastIntern (string) {
container[string] = true;
var interned = Object.keys(container)[0];
delete container[interned];
return interned;
};