我进行了一些测试。第一种方法略微更快,但在重负荷使用下也不足以产生任何真正的差异...... 除非当sCompOp
可能是一个非常长的字符串时。因为第一种方法搜索的是固定长度的字符串,所以无论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中测试通过。