いくつかのテストを実行しました。最初の方法はわずかに高速ですが、非常に長い文字列になる可能性がある場合を除いて、頻繁に使用しても実際の違いを生むには十分ではありません。sCompOp
最初のメソッドは固定長の文字列を検索するため、その実行時間は取得の長さに関係なく非常に安定していますsCompOp
が、2 番目のメソッドは の全長にわたって反復する可能性がありsCompOp
ます。
また、2 番目の方法は、無効な文字列に一致する可能性があります。「何とか何とか <= 何とか何とか」はテストを満たします...
他の場所で演算子を解析する作業を行っている可能性が高いことを考えると、どちらのエッジケースも問題になるとは思えません。ただし、そうでない場合でも、式を少し変更するだけで両方の問題が解決します。
/^(>=|<=|<>)$/
テスト コード:
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 でテスト済み