我进行了一些测试。第一种方法稍微快一些,但即使在大量使用的情况下也不足以产生任何真正的区别......except when sCompOp
可能是一个很长的字符串。因为第一种方法搜索的是固定长度的字符串,所以无论多长它的执行时间都很稳定sCompOp
gets,而第二种方法可能会迭代整个长度sCompOp
.
此外,第二种方法可能会匹配无效字符串 - “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 中测试