JavaScript样式/优化:String.indexOf()v.Regex.test()

我最近遇到了这段 JavaScript代码
if (",>=,<=,<>,".indexOf("," + sCompOp + ",") != -1)

我很感兴趣,因为写这个测试我会做的:

if (/(>=|<=|<>)/.test(sCompOp))

这只是一个风格的差异,还是另一个代码的作者知道我没有的优化?或者也许有不同的好的理由这样做,还是不使用正则表达式?

在我看来,使用String.indexOf()对于读取更困难一点(但是我对正则表达式很满意),但是有些实例可能比编写等效的正则表达式更好?

“更好”可能更快或更有效率(虽然显然这取决于浏览器的JavaScript引擎),或者其他一些我不知道的原因.任何人都可以启发我吗?

解决方法

我进行了一些测试.第一种方法稍微快一点,但是不足以使得在很大的使用下产生真正的区别,除非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 ("," + 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,铬0.2.149.30

相关文章

什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据...
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:...
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面