MX *_*X D 2 c# garbage-collection
今天我注意到我制作的一个小程序经常在程序生命周期的前10~20秒内触发GC.之后它再也几乎没有触发.

在这段时间内只运行一个函数,即下面的函数.获取~2k的文件路径,并过滤掉大部分文件路径.
public static string[] FilterFiles(string path)
{
// Fetch the files from given directory
var files = Directory.GetFiles(path);
// Delete all files that are to small
foreach (string file in files)
{
string fullFile = default(string);
try
{
fullFile = File.ReadAllText(file);
}
catch
{
continue;
}
if (fullFile.Length < Settings.MinimumFileSize)
{
File.Delete(file);
}
}
// Obtain the new list without the small files
List<string> cleanFiles = new List<string>(Directory.GetFiles(path));
List<string> cleanReturn = new List<string>(Directory.GetFiles(path));
// Remove files we have handled before
foreach (string file in cleanFiles)
{
if (File.Exists(Settings.ExtractFolder + "\\" + file.Substring(file.LastIndexOf('\\') + 1) + "_Extract.xml"))
{
cleanReturn.Remove(file);
}
}
return cleanReturn.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
GC在这段时间内经常触发这种情况是否正常?
嗯,是.您正在创建大量具有较短生命周期的对象,并且这些对象会尽快处理.
尽量不要阅读整个文件.相反,只需获取FileInfo文件大小即可.
这里列举两次目录列表,这也是不必要的:
List<string> cleanFiles = new List<string>(Directory.GetFiles(path));
List<string> cleanReturn = new List<string>(Directory.GetFiles(path));
Run Code Online (Sandbox Code Playgroud)
此外,由于字符串连接,还会创建大量字符串:
Settings.ExtractFolder + "\\" + file.Substring(file.LastIndexOf('\\') + 1) + "_Extract.xml"
Run Code Online (Sandbox Code Playgroud)
使用StringBuilder或string.Format在那里,并尽可能在前面尽可能多地做.