Qt QDomElement性能问题

Qt QDomElement performance issue

本文关键字:问题 性能 QDomElement Qt      更新时间:2023-10-16

我正在编写一个用于处理GPX文件的应用程序,在使用QDomElement类读取大型XML文档时遇到了性能问题。带有包含数千个路点的GPS路径的文件可能需要半分钟才能加载。

这是我读取路径(路线或轨道)的代码:

void GPXPath::readXml(QDomElement &pathElement)
{
    for (int i = 0; i < pathElement.childNodes().count(); ++i)
    {
        QDomElement child = pathElement.childNodes().item(i).toElement();
        if (child.nodeName() == "trkpt" ||
            child.nodeName() == "rtept")
        {
            GPXWaypoint wpt;
            wpt.readXml(child);
            waypoints_.append(wpt);
        }
    }
}

在用苹果仪器分析代码时,我注意到QDomNodeListPrivate::createList()负责大部分计算时间,它被QDomNodeList::count()和QDomNodeList::item()调用。

这似乎不是迭代QDomElement的子元素的有效方式,因为列表似乎是为每个操作重新生成的。我应该使用什么方法?

我尝试了这个

void GPXPath::readXml(QDomElement &pathElement)
{
    QDomElement child = pathElement.firstChildElement();
    while (!child.isNull())
    {
        if (child.nodeName() == "trkpt" ||
            child.nodeName() == "rtept")
        {
            GPXWaypoint wpt;
            wpt.readXml(child);
            waypoints_.append(wpt);
        }
        child = child.nextSiblingElement();
    }
}

事实证明,它的速度快了15倍。通过使用SAX,我可能可以更快地完成这项工作,但现在就可以了。

您应该考虑使用QT SAX而不是DOM。SAX解析器通常不会将整个XML文档加载到内存中,并且在

这样的情况下很有用