XmlDocument与XmlReader读取Xml占用内存和速度比较示例
代码1:
private voidbutton1_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == DialogResult.OK)
{
DateTime startTime = DateTime.Now;
XmlDocument xmlDocument = newXmlDocument();
xmlDocument.Load(fileDialog.FileName);
foreach (XmlNodexmlNode in xmlDocument.ChildNodes)
{
}
DateTime endTime = DateTime.Now;
double milliseconds = (endTime -startTime).TotalMilliseconds;
label1.Text= "Read Finished in " +milliseconds.ToString() + " Milliseconds";
}
}
选择大小37MB的xml文件,这个程序占用内存158MB,读取时间2000 Milliseconds左右
代码2:
private voidbutton1_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == DialogResult.OK)
{
DateTime startTime = DateTime.Now;
XmlReader xmlReader = XmlReader.Create(fileDialog.FileName);
while (xmlReader.Read())
{
}
DateTime endTime = DateTime.Now;
double milliseconds = (endTime -startTime).TotalMilliseconds;
label1.Text= "Read Finished in " +milliseconds.ToString() + " Milliseconds";
}
}
选择同一个xml文件,程序占用内存34MB,读取时间不到500Milliseconds。
因此,可以考虑读取大文件时使用XmlReader,经常随机读取小文件时使用XmlDocument。