Java StringBuilder to concatenate strings - Sample Code

Concatenation of string using “+” operator can be seen very common in sysout,logDebug statements.This will have an impact on the performance. it should be avoided to improve the performance.instead you can use StringBuilder.append().This will really improve the efficiency of CPU utilization by 2.3 times compare with concatenation of string using “+”operator.

Please find the usage below

System.out.println("request params :"
                    + " contextPath=" + pRequest.getContextPath()
                    + ", " + PATH_Info + "=" + pathInfo
                    + ", " + BASIC_AUTH + "=" + basicAuth
                    + ", " + FORM_AUTH + "=" + formAuth
                    + ", " + FORCE_LOCALE_PARAM + "=" + forceLocale
                    );

The above concatenation can be achieved as given below,

String [] stringConcatArray  = {"request params :"," contextPath=",pRequest.getContextPath),PATH_Info,"=",pathInfo,BASIC_AUTH,"=",basicAuth,FORM_AUTH,"=",formAuth,
FORCE_LOCALE_PARAM,"=",forceLocale};

System.out.println(stringConcat(stringConcatArray));

Add below method in your StringUtil Class.Any number of string arguments can be passed to this method to get it concatenated to one string.

public static String stringConcat(String args[]) {
  StringBuilder builder = new StringBuilder();
  for (String strVal : args)
   builder.append(strVal);
  return builder.toString();
 }

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...