mowienay
mowienay

Reputation: 1354

Looping XML with the lowest complexity

I am using Java DOM parser to parse XML files. Performance is important to me and I need to write the most optimized code. I noticed that XMLs to be processed have a lot of nested tags (It can reach 5 levels in depth) and I have to retrieve information of all levels.

The dummy solution I implemented is to have nested loops each loop retrieves the node's children and passes it to the next loop.

This is a very bad practice on the level of performance and complexity as code complexity reaches O(n^5). Please, find how it can go on the code level below.

I believe divide and conquer algorithms might work in this case.

Do any of you have any suggestions to have a more optimized code to have better performance?

for (int temp = 0; temp < contractDetails.getLength(); temp++){ Node detail = contractDetails.item(temp); System.out.println(detail.getNodeName()); NodeList detail2 = detail.getChildNodes();

      for (int temp2 = 0; temp < detail2.getLength(); temp2++){
      .........
          for (int temp3 = 0; temp < detail3.getLength(); temp3++){
              ...............
          }

      }
   }

Upvotes: 0

Views: 119

Answers (1)

Michael Kay
Michael Kay

Reputation: 163458

Firstly, if you are interested in performance, don't use DOM. Other tree models in Java, such as XOM, are much faster, and easier to use as a bonus.

Secondly, your code with 5 nested loops is not O(n^5). The total number of iterations of the innermost loop is equal to the number of nodes in the document, so it's O(n) in the size of the document.

Upvotes: 1

Related Questions