【问题标题】:Qt QDomElement performance issueQt QDomElement 性能问题
【发布时间】:2012-07-21 18:55:50
【问题描述】:

我正在编写一个使用 GPX files 的应用程序,但在使用 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);
        }
    }
}

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

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

【问题讨论】:

    标签: c++ xml qt


    【解决方案1】:

    我试过这个

    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 可能会更快,但现在就可以了。

    【讨论】:

    • 我可以确认这在我的应用程序中也是一个很大的改进。我经过了 10 到 2 秒的解析时间。正如你所说,问题是调用 QDomNodeListPrivate::createList() 的 QDomNodeList::count() 方法......非常慢。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-10-17
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 2022-01-04
      • 2011-08-03
      相关资源
      最近更新 更多