title: Fast way to append blank strings.
body: <p>I have to generate a single string containing all the data members of a class. For example, if a class definition is </p>
  
  <pre><code>class A    
   {
     private String field1;
     private String field2;
     private String field3;
     ...
     ...
   }
  </code></pre>
  
  <p>Then I want to generate a string that will contain field1, field2 and field3 in that order. However, the additional thing that I want to do is ensure the following rules - </p>
  
  <pre><code>  field1 is of length 20. If it is less than 20, pad it with blank spaces.
    field2 is of length 10. If it is less than 10, pad it with blank spaces.
    field1 is of length 15. If it is less than 15, pad it with blank spaces.
    ...
    ...
  </code></pre>
  
  <p>I plan to use a helper class to build this string. I want to use a StringBuilder to get the final string. So I have something like - </p>
  
  <pre><code>  StringBuilder builder = new StringBuilder();
  
    Helper.addString(field1,20,builder);
  </code></pre>
  
  <p>Now the implmentation of this addString function is what I am concerned about. This function will be called thousands of times for different classes. So I want to make it as efficient as possible. The question is, <strong>what is the most efficient way</strong>? Currently, I have the following implementation - </p>
  
  <pre><code> public static void addString(String field, int totalLengthOfField, StringBuilder builder)
   {
      int lengthOfField = field.length();
      int numberOfBlankSpacesToPutAfterString = totalLengthOfField - lengthOfField;
  
      if(numberOfBlankSpacesToPutAfterString &gt;=0)
        {
          builder.append(field);
          for(int i=1; i&lt;= numberOfBlankSpacesToPutAfterString; i++)
            {
              builder.append(" "); // append a blank space
            }
        }
      else
        {
          // throw exception - field is longer than the maximum allowed length.
        }
   }
  </code></pre>