izb
izb

Reputation: 51820

Fastest way to escape a String in JavaME

I have a method that looks like this:

public static String escape(String text)
{
   String r = replace(text, "\\", "\\\\");
   r = replace(r, "\r", "\\r");
   r = replace(r, "\b", "\\b");
   r = replace(r, "\t", "\\t");
   r = replace(r, "\n", "\\n");
   r = replace(r, "\f", "\\f");
   return r;
}

Is there a faster, less brutal way to do this and if so what would that way look like?

Note that this is J2ME, so no Apache commons, and no regex.

Upvotes: 3

Views: 1119

Answers (4)

Fostah
Fostah

Reputation: 11796

I would do something like below. You'll have to benchmark it for your own target devices to make sure, but I think it will certainly be faster since you are not creating a new String object for every replace. And, it will be better from a creating garbage on the heap standpoint, which may or may not help with heap fragmentation.

public static String escape(String text) { 
    if(text == null) {
        return null;
    }

    int numChars = text.length();
    char ch;
    StringBuffer sb = new StringBuffer();
    for(int i = 0; i < numChars; i++) {
        ch = text.charAt(i);

        switch(ch) {
            case '\\':  { sb.append("\\\\"); break; }
            case '\r':  { sb.append("\\r"); break; }
            case '\b':  { sb.append("\\b"); break; }
            case '\t':  { sb.append("\\t"); break; }
            case '\n':  { sb.append("\\n"); break; }
            case '\f':  { sb.append("\\f"); break; }
            default: {
                sb.append(ch);
                break;
            }
        }
    }
    return sb.toString();
}

Upvotes: 4

Brian Agnew
Brian Agnew

Reputation: 272347

Once it works (comment noted above), the simplest way to speed it up is to perform the replacements using a StringBuffer.

But, have you measured this ? Is it a bottleneck ? I would suggest you do this before expending energy on optimisations.

Upvotes: 1

Billy Bob Bain
Billy Bob Bain

Reputation: 2895

Do you mean "fast" for the developer or performance? If it's the latter, then use a char array & do it all yourself. It will be much faster since you can do it in one pass.

Upvotes: 2

iffi
iffi

Reputation: 53

hm can't you just use

public static String escape(String text)
{
   String r = replace(text, "\", "\\");
   return r;
}

Upvotes: -3

Related Questions