C#3.5で次のことを行うための最速の方法は何ですか?
- ディレクトリ内のファイルを反復処理します
- ファイルのレコードを読み取ります(247文字の固定長)
- 各レコードの固定長文字列を構造体またはクラスに変換します。
ありがとう
C#3.5で次のことを行うための最速の方法は何ですか?
ありがとう
これは比較的速く書くことができます:
var myStructs =
from file in Directory.GetFiles(".", "*.*", SearchOption.TopDirectoryOnly)
select ConvertFileToStructs(File.ReadAllText(file));
これがパフォーマンスの面で可能な限り最速の方法である場合はどうでしょうか。おそらくそうではありませんが、大きな違いはありません。パフォーマンスに影響を与えるのは、ConvertFileToStructs()関数内での逆シリアル化の実装です。しかし、これに答えるには、ファイルの特定の形式を知る必要があります。
コメントを読んでください。次の解析をお勧めします。
List<MyStruct> ConvertFileToStructs(string content, int[] mapping)
{
var records = new List<MyStruct>();
int length = content.Length();
for(int i = 0; i < length; i += 247)
records.Add(ConvertRecordToStruct(content.Substring(i,247), mapping));
return records;
}
MyStruct ConvertRecordToStruct(string record, int[] mapping)
{
MyStruct s;
s.Field1 = record.Substring(mapping[0], mapping[1]);
//set other fields
return s;
}
このコードはおそらくパフォーマンスのために最適化できますが、特にディスクへのI / Oが含まれ、Substring()が非常に高速であるため、劇的に変化するとは思いません(http://dotnetperls.com/substringを参照)。もちろん、これを自分のマシンでテストする必要があります。
ファイルを処理するカスタムクラス
class customFile
{
string fileText;
public string FileText
{
get { return fileText; }
set { fileText = value; }
}
}
すべてのテキストを読む
string[] filePaths = Directory.GetFiles(dirPath);
List<customFile> customFiles = new List<customFile>();
foreach (string file in filePaths)
{
customFiles.Add(new customFile { FileText = File.ReadAllText(file) });
}