The 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 violent way to do this, and if so, what would it look like?

Note that this is J2ME, so there is no Apache and no regular expression.

+3
source share
4 answers

I would do something like below. You will need to compare it for your target devices to make sure, but I think it will certainly be faster since you are not creating a new String object for each replacement. And it will be better from creating garbage on the heap point, which may or may not help with fragmentation of the heap.

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();
}
+4
source

"" ? , char . , .

+2

Once it works (the comment noted above), the easiest way to speed it up is to make replacements using StringBuffer .

But, did you measure it? Is this a bottleneck? I suggest you do this before spending energy on optimization.

+1
source

hm you can't just use

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

Source: https://habr.com/ru/post/1716678/


All Articles