KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > log4j > performance > ListVsVector


1 /*
2  * Copyright 1999-2005 The Apache Software Foundation.
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 org.apache.log4j.performance;
18
19
20 import java.util.Vector JavaDoc;
21
22 /**
23
24    Compares the performance of looping through a list versus a Vector.
25
26    Chain looping is *20* times faster than vector access on JDK 1.1.7B on NT
27
28 */

29 public class ListVsVector {
30
31   static int RUN_LENGTH = 1000000;
32   static Vector JavaDoc v = new Vector JavaDoc();
33   static Chain head;
34   static String JavaDoc tmp;
35
36   static
37   public
38   void main(String JavaDoc[] args) {
39
40     v.addElement("aaa");
41     v.addElement("bbb");
42     v.addElement("ccc");
43     v.addElement("ddd");
44     v.addElement("eee");
45     
46     Chain c = new Chain("aaa");
47     head = c;
48     c.next = new Chain("bbb"); c = c.next;
49     c.next = new Chain("ccc"); c = c.next;
50     c.next = new Chain("ddd"); c = c.next;
51     c.next = new Chain("eee");
52     double t;
53     t = loopChain();
54     System.out.println("Looping thourgh the chain took " + t);
55
56     t = loopVector();
57     System.out.println("Looping thourgh the vector took " + t);
58
59   }
60
61   static
62   double loopChain() {
63     long before = System.currentTimeMillis();
64     Chain c;
65     for(int i = 0; i < RUN_LENGTH; i++) {
66       c = head;
67       while(c != null) {
68     tmp = c.s;
69     c = c.next;
70       }
71     }
72     return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH;
73   }
74
75   static
76   double loopVector() {
77     long before = System.currentTimeMillis();
78     int size = v.size();
79     for(int i = 0; i < RUN_LENGTH; i++) {
80       for(int j = 0; j < size; j++)
81     tmp = (String JavaDoc) v.elementAt(j);
82     }
83     return (System.currentTimeMillis() - before)*1000.0/RUN_LENGTH;
84   }
85
86   static class Chain {
87     public String JavaDoc s;
88     public Chain next;
89
90     Chain(String JavaDoc s) {
91       this.s = s;
92     }
93     
94     void setNext(Chain c) {
95       next = c;
96     }
97   }
98 }
99
Popular Tags