我想为JavaScript枚举编写一个小库.对我来说,我需要决定如何存储枚举值.因此,我想在比较时使用最快的方法,但我也想要一些可调试的东西,所以我在使用字符串或数字之间徘徊.我知道我也可以使用对象,但这将是另一个问题
例如
// I don't want this because when debugging, you'd see just the value 0
var Planets = {Earth:0, Mars:1, Venus: 2}
// I'd prefer this so that Planets.Earth gives me a nice readable value ("Earth")
var Planets = {Earth: 'Earth', Mars: 'Mars'}
Run Code Online (Sandbox Code Playgroud)
但是我担心当我比较它们时if (myPlanet === Planet.Earth),字符串比较可能会花费更长的时间(比如它是否处于紧密循环中).这应该是这种情况,因为http://ecma-international.org/ecma-262/5.1/#sec-11.9.6说
如果Type(x)是String,则如果x和y完全相同的字符序列(相应位置的长度和字符相同),则返回true; 否则,返回false.
但是当我写一个测试用例时,我发现他们花了相同的时间http://jsperf.com/string-comparison-versus-number-comparison/2所以它似乎不是在扫描整个字符串.
我知道这可能是一个微优化,但我的问题是:是否使用指针进行字符串相等比较,因此与数字相等比较一样快?