1

大きなファイルをメモリにロードする必要があり、部分文字列を見つけたい。どちらの方法が速いですか?

// アプリケーションの初期化

string instring  = "which is faster find in string or list..."; // large string +- 150MB
List<string> inlist = new List<string>();
foreach (string word in instring) {
    inlist.Add(word);
}

// ボタンクリック

if (instring.Contains("find")) {
  ...
}

また

if (inlist.Contains("find")) {
  ...
}

私の場合、文字列検索が最速であるという測定を行いました。

Singel search:
Boyer-Moore search found - elapsed: 00:00:00.0025893
String search found - elapsed: 00:00:00.0026120
List search not found - elapsed: 00:00:00.0026394

Multi search:
Boyer-Moore search found - elapsed: 00:00:00.0027377
Boyer-Moore search found - elapsed: 00:00:00.0028308
Boyer-Moore search found - elapsed: 00:00:00.0029269
Boyer-Moore search found - elapsed: 00:00:00.0030234
Boyer-Moore search found - elapsed: 00:00:00.0031210

String search found - elapsed: 00:00:00.0032474
String search found - elapsed: 00:00:00.0032653
String search found - elapsed: 00:00:00.0032832
String search found - elapsed: 00:00:00.0033015
String search found - elapsed: 00:00:00.0033201


List search not found - elapsed: 00:00:00.0033629
List search not found - elapsed: 00:00:00.0033826
List search not found - elapsed: 00:00:00.0033961
List search not found - elapsed: 00:00:00.0034155
List search not found - elapsed: 00:00:00.0034345
4

2 に答える 2

4

あなたは根本的に異なることをテストしています。

たとえば、実際に「find」を探して、次のようなファイルを取得したとします。

If you're interested in finding the answer, make sure you know the question.

それを単語ごとに 1 つの文字列のリストに分割すると、「検索」という単語の一部にすぎないため、「検索」は表示されません。ただし、これは部分文字列であるため、string.Containsyouを使用すると見つかります。

最初に目的の動作を解決し、最も単純で最も洗練された方法で実装してから、パフォーマンスを測定する必要があります。それが目的のパフォーマンスを満たしていれば、完了です。そうでない場合は、改善を試みることができます。各ポイントで測定し、目的の動作が得られていることを確認します。

于 2012-11-17T09:43:37.147 に答える
0

バッファを介してファイルをストリーミングし、行ごとに分析する方がおそらく良いでしょう。どちらの場合も、ファイル全体を読み取る必要がありますが、リストを作成するときは、完全なファイル コンテンツをメモリに格納する必要があります。

Microsoft msdnの c# の例

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                string line;
                string subString = "find this";
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    if ( line.Contains(substring) ) 
                    {
                         Console.WriteLine("Found string");
                         break;
                    }
                }
            }
        }
        catch (Exception e) 
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}
于 2012-11-17T09:46:46.193 に答える