>01      public static String escapeString (String str) {
>02
>03       int escCount = 0;
>04       int len = str.length();
>05       char c;
>06
>07       // Count number of chars that need escaping.
>08       for (int i=0; i<len; i++) {
>09      c = str.charAt(i);
>10      if (c == '\\' || c == '\"')
>11        escCount++;
>12       }
>13
>14       if (escCount > 0) {
>15
>16      StringBuffer buf = new StringBuffer(str.length() + escCount);  // !
>17
>18      for ( int idx = 0; idx < str.length(); idx++ )  {              // !
>19        char ch = str.charAt( idx );
>20        switch ( ch ) {
>21        case '"':  buf.append( "\\\"" ); break;                      // !
>22        case '\\': buf.append( "\\\\" ); break;                      // !   
>23        default:   buf.append( ch );     break;
>24        }
>25      }
>26
>27      return buf.toString();
>28       }  
>29       else 
>30      return str;
>31     }

Hi,
Here are 2 remarks :

1. : line (16,18)
You define the field 'len' but you don't use it everywhere.
So you have lot's of function calls (str.length()).



2. :line (21,22)
If you look at the source of java.lang.StringBuffer it seems that
buf.append( '\\' ).append( '\"' );    is cheaper than a
buf.append( "\\\"" );

java.lang.StringBuffer :

    public synchronized StringBuffer append(char c) {
        int newcount = count + 1;
        if (newcount > value.length)
            expandCapacity(newcount);
        value[count++] = c;
        return this;
    }

    public synchronized StringBuffer append(String str) {
        if (str == null) {
            str = String.valueOf(str);
        }
        int len = str.length();                         // !
        int newcount = count + len;
        if (newcount > value.length)
            expandCapacity(newcount);                   // !
        str.getChars(0, len, value, count);
        count = newcount;
        return this;
    }


Regards,

Ralf

Reply via email to