我进行了一些测试。第一种方法稍微快一点,但即使在大量使用的情况下也不足以产生任何真正的影响......除非sCompOp
可能是一个很长的字符串。因为第一种方法搜索的是一个固定长度的字符串,所以无论get多长时间它的执行时间都很稳定sCompOp
,而第二种方法可能会遍历整个长度sCompOp
。
此外,第二种方法可能会匹配无效字符串-“blah blah blah <= blah blah”满足测试...
鉴于您可能正在其他地方解析运算符,我怀疑任何一种极端情况都会成为问题。但即使不是这种情况,对表达式进行小的修改也可以解决这两个问题:
/^(>=|<=|<>)$/
测试代码:
function Time(fn, iter)
{
var start = new Date();
for (var i=0; i<iter; ++i)
fn();
var end = new Date();
console.log(fn.toString().replace(/[\r|\n]/g, ' '), "\n : " + (end-start));
}
function IndexMethod(op)
{
return (",>=,<=,<>,".indexOf("," + op + ",") != -1);
}
function RegexMethod(op)
{
return /(>=|<=|<>)/.test(op);
}
function timeTests()
{
var loopCount = 50000;
Time(function(){IndexMethod(">=");}, loopCount);
Time(function(){IndexMethod("<=");}, loopCount);
Time(function(){IndexMethod("<>");}, loopCount);
Time(function(){IndexMethod("!!");}, loopCount);
Time(function(){IndexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);
Time(function(){IndexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);
Time(function(){RegexMethod(">=");}, loopCount);
Time(function(){RegexMethod("<=");}, loopCount);
Time(function(){RegexMethod("<>");}, loopCount);
Time(function(){RegexMethod("!!");}, loopCount);
Time(function(){RegexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);
Time(function(){RegexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);
}
timeTests();
在 IE6、FF3、Chrome 0.2.149.30 中测试