Varargs and debug print

I  had not used the Varargs feature available in Java 5 until recently. As expected, it was pretty easy to use. From the performance point of view, I was looking mainly at Object allocation and other performance costs for a specific problem in one of our applications.

We had debug print messages like the one below sprinkled in several parts of the application. Yes, I know, this problem would not even be present if we had used logging correctly. Well, now that we are stuck with it, I was curious to know how the performance, especially Object allocation statistics would change if I used varargs.

...
javax.xml.datatype.DatatypeFactory factory;
javax.xml.datatype.XMLGregorianCalendar date;
...
debugPrint ("In getData: Factory = " + factory + " date = " + date);
...

public void debugPrint (String msg) {
   if (debug)
      System.out.println (msg);
}

Even with the debug flag set to false, this causes the creation of a StringBuilder, several Strings as well as char[] objects (My microbenchmark showed 13 char[] objects/1904 bytes, 4 Strings/98 bytes and 1 StringBuilder/16 bytes), as well as the additional cost of generating String representation of the factory and date objects. Even though these are relatively inexpensive operations, if used repeatedly, these can add up and cause poor performance.

I rewrote the debugPrint method and its usage as follows -

debugPrint ("Factory = ", factory, " date = ", date);

public void debugPrint (Object ... msg) {
   if (!debug || msg==null)
       return;
   StringBuilder strb = new StringBuilder();
   for (int i=0; i<msg.length; i++)
      strb.append (msg[i].toString());
  }
  System.out.println (strb.toString());
}

As far as Object allocations go, this created just one Object[] (size=32 bytes). Additionally, no other work was carried out since debug flag was set to false.  So overall, this is a pretty good solution.

Note: Varargs does support use of primitives through autoboxing in which case some additional objects may be created.

Comments:

Post a Comment:
Comments are closed for this entry.
About

binu

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today