2008年12月28日 日曜日 0:26:17
JavascriptでindexOfとmatchの速度がちょっと気になった
最近Firefox3でindexOfと正規表現(match)による速度測定をしたけど、速度に差がなかったよ・・・的な記事を見かけた。
そんなことはないはず!とか思いながらも、ちょっと気になったんで簡単に試してみた。
ちょっと元記事がどこいっちゃったのか、紛失しちゃったんですが・・・(>_<);;;
実行コード
というわけで、以下のコードを用意して実行してみた。
(function(){
var $measure = function() {
this.compact = /s+/g;
};
$measure.prototype.time = function()
{
return (new Date()).getTime();
};
$measure.prototype.exec = function(func)
{
var i=0;
this.st = this.time();
for (;i<10000;i++) func();
this.ft = this.time();
return this.result = func.toString().replace(this.compact, ' ') +
' (' + (this.ft - this.st) + ')';
};
var $M = new $measure(),
text = 'abcdefghijklmnopqrstuvwxyz',
ward = 'lmn',
reg = /lmn/;
alert($M.exec(function()
{
text.indexOf(ward);
}) + 'n'+ $M.exec(function()
{
text.match(/lmn/);
}) + 'n'+ $M.exec(function()
{
text.match(reg);
}));
})();
やっつけだったんで、突っ込みどころもあるだろうけど、さておき。
処理自体は文字列「abcdefghijklmnopqrstuvwxyz」の中から、「lmn」を探し出すというだけ。
結果
- indexOfは5~6ミリ秒前後。
- match使用で正規表現を毎回作成すると27~30ミリ秒前後。
- match使用で正規表現を変数から割り当てた場合は26~28ミリ秒前後。
というわけで、予想通りうちの環境ではindexOfが速い。
正規表現オブジェクトを変数代入した場合と、毎回作成した場合での結果がたまに気になる( ̄□ ̄;)
基本は変数に入れてる方が速いんだけど、たまに逆転したり。
いろいろなプロセスが動いてる状態でテストしてるから、今回はその辺りの誤差だと勝手に納得することにする。
目的は果たせたし。
記事もやっつけ(゜∀゜)
それにしても元記事どこいったんだろう・・・(´・ω・`)
実行環境
- OS: Windows XP SP3
- CPU: Pen4 3.2G
- メモリー: 3G
- Firefox3.0.5
おまけ
せっかくなので、ブックマークレットを載せておきます。
indexOfとmatchの速度比較
追記:2009-1-21
正規表現とindexOfを比較するなら、大文字小文字の対応も必要だなと思ってtoLowerCaseを加えた。
正規表現は大文字小文字の区別なし、indexOf()はtoLowerCase()を使用した文字を検索するよう変更。
ほぼ一緒だけど、コードは以下の通り。
(function(){
var $measure = function() {
this.compact = /s+/g;
};
$measure.prototype.time = function()
{
return (new Date()).getTime();
};
$measure.prototype.exec = function(func)
{
var i=0;
this.st = this.time();
for (;i<10000;i++) func();
this.ft = this.time();
return this.result = func.toString().replace(this.compact, ' ') +
' (' + (this.ft - this.st) + ')';
};
var $M = new $measure(),
text = 'abcdefghijklmnopqrstuvwxyz',
ward = 'lmn',
reg = /lmn/i;
alert($M.exec(function()
{
text.indexOf(ward);
}) + 'n'+ $M.exec(function()
{
text.indexOf(ward.toLowerCase());
}) + 'n'+ $M.exec(function()
{
text.match(/lmn/i);
}) + 'n'+ $M.exec(function()
{
text.match(reg);
}));
})();
結果
- indexOfでtoLowerCaseなしは6ミリ秒前後。
- indexOfでtoLowerCaseありは9ミリ秒前後。
- match使用で正規表現の大文字小文字の区別なしを毎回作成すると28ミリ秒前後。
- match使用で正規表現の大文字小文字の区別なしを変数から割り当てた場合は28ミリ秒前後。
toLowerCaseを加えた分少し遅くなったけど、やっぱり正規表現よりは速いらしい。
こちらも、ブックマークレットを載せておきます。
indexOfとmatchの速度比較(toLowerCase追加、正規表現は大文字小文字の区別なし)
関連記事:
[MDIEスクリプト] select2zip.jsを更新
[clipFolder.js] MDIEでクリップボードからサクッとフォルダを作成
AIR用のSQLiteライブラリ「AirDB.js」
トラックバック URL :
コメント (0)