Search code examples
javaoptimizationstringbuilder

Fast way to append blank strings.


I have to generate a single string containing all the data members of a class. For example, if a class definition is

class A    
 {
   private String field1;
   private String field2;
   private String field3;
   ...
   ...
 }

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 -

  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.
  ...
  ...

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 -

  StringBuilder builder = new StringBuilder();

  Helper.addString(field1,20,builder);

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, what is the most efficient way? Currently, I have the following implementation -

 public static void addString(String field, int totalLengthOfField, StringBuilder builder)
 {
    int lengthOfField = field.length();
    int numberOfBlankSpacesToPutAfterString = totalLengthOfField - lengthOfField;

    if(numberOfBlankSpacesToPutAfterString >=0)
      {
        builder.append(field);
        for(int i=1; i<= numberOfBlankSpacesToPutAfterString; i++)
          {
            builder.append(" "); // append a blank space
          }
      }
    else
      {
        // throw exception - field is longer than the maximum allowed length.
      }
 }

Solution

  • Java has the Formatter class that supports creating strings with width definitions for specific fields, much like sprintf() in C. String.format() also uses a Formatter object internally.

    That said, Formatter is not all that fast. You might be better off appending strings manually to a StringBuilder and using a small cache of strings with various number of spaces, to avoid always appending single spaces...

    For example, if you know that the padding size will always be less than 20 spaces, you could just create a String[] table with strings that have 0, 1, 2... spaces and completely skip the loop. If there is no such restriction, you could still append blocks of, say, 20 spaces at once until you reach the necessary padding size.