简体   繁体   中英

jQuery - Improving selector performance when processing XML

I am processing an XML file that has very slow performance when selecting Nodes with XPath style selectors.

Here is part of the code that runs particularily slow

for (i=0;i<lanes.length;i++)
    htmlContents += GetLaneInfo($(this).find("Lane[num='"+lanes[i]+"']").attr('avg'));

I believe the slowest part of this code is the Lane[num=X] selector, how can I improve the performance of this? Can I cache $(this).find("Lanes") and then search through them later on?

XML Sample:

<Data time="10:50">
    <Lane num="102" avg="2.0"/>
    <Lane num="103" avg="2.0"/>
    <Lane num="104" avg="2.0"/>
    <Lane num="112" avg="2.0"/>
    <Lane num="113" avg="2.0"/>
    <Lane num="114" avg="2.0"/>
    <Lane num="115" avg="2.0"/>
    <Lane num="122" avg="0.9"/>
    <Lane num="123" avg="1.0"/>
    <Lane num="124" avg="1.0"/>
    <Lane num="132" avg="0.7"/>
    <Lane num="134" avg="0.7"/>
    <Lane num="142" avg="0.8"/>
    <Lane num="153" avg="0.4"/>
    <Lane num="154" avg="0.6"/>
</Data>

try this :

http://jsperf.com/1f

Ive managed to increase the speed. 在此输入图像描述

ps it is based on the fact that all lanes are in the same order in each xml node.

I know this is late, but here's a viable high performance solution:

http://jsperf.com/1f/3

在此输入图像描述

Using XML parsing for such simple markup is a waste. If you want speed using indexOf and substring is the superior method.

http://jsperf.com/1f/2

I edited @Royi Namir 's jsperf and added my own version (aptly named "screw xml"). It runs 2x faster than his optimized XML parsing version.

Here's the code that would aline with the OP's example from the question. The "xml" variable is just a string that represents the XML.

var find = '';
var start = -1;
var end = -1;
var skip1 = 0;
var skip2 = ' avg="'.length;
//
for (i=0;i<lanes.length;i++) {
  find = 'num="' + lanes[i] + '"';
  skip1 = find.length;
  end = -1;
  start = xml.indexOf(find, 0);
  while (start != -1) {
    start = start + skip1 + skip2;
    end = xml.indexOf("\"/>", start);
    htmlContents += GetLaneInfo(xml.substring(start, end));
    start = xml.indexOf(find, end);
  }
}

In reality you probably don't want to use a version like the above because it hinges on the XML being formatted uniformly (see: "skip2" variable/constant). But if you really want performance/speed doing it this way is the fastest by far.

好吧,在你的示例xml数据中,我们可以看到num属性已经排序,如果是这样的话,请尝试为该数据实现http://en.wikipedia.org/wiki/Bisection_method :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM