我的网络服务每分钟写入数千笔交易,我们将它们保存在硬盘上。
我正在测试保存这些文件的不同方法,并使用标准 IO 和 MemoryMapped 文件进行了一些测试。在我的结果中,使用 MemoryMapped 文件写入文件(20 k 文本文件)大约比标准 IO 快 4 倍,而且我没有发现任何缺点。
由于我对这项技术没有太多经验,您认为我在使用它们时可能会遇到任何问题,或者您没有看到任何缺点吗?
谢谢!
EDIT 1,这里是来源:
namespace FileWritingTests.Writers {
public class MappedFileWriter : ITestWriter {
public void Write(string content, string path,string id) {
Byte[] data = System.Text.Encoding.UTF8.GetBytes(content);
using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
using (MemoryMappedFile memoryMapped = MemoryMappedFile.CreateFromFile(fileStream, id, data.Count(),
MemoryMappedFileAccess.ReadWrite, new MemoryMappedFileSecurity(), HandleInheritability.Inheritable, true)) {
var viewStream = memoryMapped.CreateViewStream();
viewStream.Write(data, 0, data.Length);
}
}
}
}
这是测试仪:
public TimeSpan Run(int iterations, Writers.ITestWriter tester, String subfolder) {
Console.WriteLine(" -- Starting test {0} with {1} file writings",subfolder, iterations.ToString());
Stopwatch stopWatch = new Stopwatch();
stopWatch.Reset();
stopWatch.Start();
for (int i = 1; i <= iterations; i++) {
tester.Write(transaction, this.path + "\\" + subfolder + "\\" + "file_" + i.ToString() + ".txt", i.ToString());
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Console.WriteLine(" -- finish test {0} with {1} file writings. Time Elapsed: {2}", subfolder, iterations.ToString(), ts.TotalMilliseconds);
return ts;
}
测试器被调用多次,并且有多种类型的测试器被调用进行比较。