Flipkart Search

Thursday 14 May 2015

Pitfalls in System.out.print or SOPs

While developing any kind of application we want that application to be as fast as we can. But it is not an easy task to achieve. Making a fast application is easy if the application is not complex. With complexity applications tends to slow down and one of the major reason is - System.out.print() of java.

Some of you may know this fact or some of you not. To understand how costly is this SOP . Let's try to build a simple method to test the speed.

    public static void main(String[] s) throws FileNotFoundException,
                                               IOException {
        String count = "";
        long total=0;
        for (int j = 0; j < 20; j++) {
            long temp=calculateCostofSOP();
            count = count + String.valueOf(temp) + " ";
            total=total+temp;
        }
        System.out.println(count);
        System.out.println(total);
    } 

This loop iterator 20 times to have a clear picture of COST of SOP. Let's now have our implementation of calculateCostofSOP

    public static long calculateCostofSOP() throws FileNotFoundException, IOException {
        FileReader fr =
            new FileReader("C:\\gre");
        
        PrintWriter pw=new PrintWriter("C:\\grew");
        BufferedReader bfr = new BufferedReader(fr);

        String line = "";
        StringBuilder sb = new StringBuilder();
        long sv = System.currentTimeMillis();
        while ((line = bfr.readLine()) != null) {
            line = line.replace("\t", "=");
            sb.append(line + "\n");
            System.out.println(line);   //comment this line while we use file out
           // pw.write(line + "\n");   //comment this line while we use console out
        }
        pw.close();
        bfr.close();
        FileWriter f =
            new FileWriter("C:\\gre");
        BufferedWriter buffW = new BufferedWriter(f);
        buffW.write(sb.toString());
        buffW.close();
        return (System.currentTimeMillis() - sv);
    }
Now look at the output we received. It took whopping 109028 milliseconds. The file "gre" was not too long. It contains data from here https://quizlet.com/47571/export.
But when I commented the SOP line and save data to the file the following output was arrived.

 //System.out.println(line);   
pw.write(line + "\n"); 
Now, it took only 1062 milliseconds.
Try it by yourself and see the results. By the above experiment we reach to following conclusion.

  • Try to avoid SOPs as much as you can
  • Never try to put SOPs inside any loop.
  • In prod applications use ADFLogger or log4j for the better performance.
  • If possible concat the String inside the loop and SOP it outside the loop.In my case it took-45216 ms



No comments:

Post a Comment