diff その2
ここのO(ND)なコード、「非常に早いコードです。diffのアルゴリズムに詳しくなければこれより早いコードは書けません。」と書いたばかりでなんだけど、ちょっといじったら2倍早くなった。前言撤回(^^;
Hashtableいらなくね?と気づいて、直接stringのGetHashCode()を取るようにしたら、手元のデータでは2倍も早くなってしまった。
ほかのいじったところと一緒に貼っときます。
public struct Option { public bool TrimSpace, IgnoreSpace, IgnoreCase; } public static Item[] DiffText( string textA, string textB ) { Option option = new Option(); return DiffText( textA, textB, option ); } public static Item[] DiffText( string textA, string textB, Option option ) { DiffData dataA = new DiffData( DiffCodes( textA, option ) ); DiffData dataB = new DiffData( DiffCodes( textB, option ) ); LCS( dataA, 0, dataA.Length, dataB, 0, dataB.Length ); return CreateDiffs( dataA, dataB ); } private static int[] DiffCodes( string text, Option option ) { // strip off all cr, only use lf as textline separator. text = text.Replace( "\r", "" ); if ( option.IgnoreCase ) text = text.ToLower(); string[] lines = text.Split( '\n' ); if ( option.TrimSpace ) for ( int i = 0; i < lines.Length; ++i ) lines[ i ] = lines[ i ].Trim(); // TODO: optimization: faster blank removal. if ( option.IgnoreSpace ) for ( int i = 0; i < lines.Length; ++i ) lines[ i ] = Regex.Replace( lines[ i ], "\\s+", " " ); int[] hashs = new int[ lines.Length ]; for ( int i = 0; i < lines.Length; ++i ) hashs[ i ] = lines[ i ].GetHashCode(); return hashs; }
ちなみに、この高速化をしたら移植したO(NP)diffより速くなってしまった…。