1 /*
2  * Copyright (C) 2011 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package benchmarks.regression;
18 
19 import com.google.caliper.Param;
20 import com.google.caliper.SimpleBenchmark;
21 import java.io.StringReader;
22 import javax.xml.parsers.DocumentBuilder;
23 import javax.xml.parsers.DocumentBuilderFactory;
24 import org.xml.sax.InputSource;
25 import org.xmlpull.v1.XmlPullParser;
26 import org.xmlpull.v1.XmlPullParserFactory;
27 
28 // http://code.google.com/p/android/issues/detail?id=18102
29 public final class XmlEntitiesBenchmark extends SimpleBenchmark {
30 
31   @Param({"10", "100", "1000"}) int length;
32   @Param({"0", "0.5", "1.0"}) float entityFraction;
33 
34   private XmlPullParserFactory xmlPullParserFactory;
35   private DocumentBuilderFactory documentBuilderFactory;
36 
37   /** a string like {@code <doc>&amp;&amp;++</doc>}. */
38   private String xml;
39 
setUp()40   @Override protected void setUp() throws Exception {
41     xmlPullParserFactory = XmlPullParserFactory.newInstance();
42     documentBuilderFactory = DocumentBuilderFactory.newInstance();
43 
44     StringBuilder xmlBuilder = new StringBuilder();
45     xmlBuilder.append("<doc>");
46     for (int i = 0; i < (length * entityFraction); i++) {
47       xmlBuilder.append("&amp;");
48     }
49     while (xmlBuilder.length() < length) {
50       xmlBuilder.append("+");
51     }
52     xmlBuilder.append("</doc>");
53     xml = xmlBuilder.toString();
54   }
55 
timeXmlParser(int reps)56   public void timeXmlParser(int reps) throws Exception {
57     for (int i = 0; i < reps; i++) {
58       XmlPullParser parser = xmlPullParserFactory.newPullParser();
59       parser.setInput(new StringReader(xml));
60       while (parser.next() != XmlPullParser.END_DOCUMENT) {
61       }
62     }
63   }
64 
timeDocumentBuilder(int reps)65   public void timeDocumentBuilder(int reps) throws Exception {
66     for (int i = 0; i < reps; i++) {
67       DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
68       documentBuilder.parse(new InputSource(new StringReader(xml)));
69     }
70   }
71 }
72