简体   繁体   English

在JavaME中转义String的最快方法

[英]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. 请注意,这是J2ME,因此没有Apache公共,也没有正则表达式。

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. 您必须为自己的目标设备进行基准测试以确保,但我认为它肯定会更快,因为您没有为每个替换创建一个新的String对象。 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();
}

Do you mean "fast" for the developer or performance? 你的意思是对开发人员或表现“快”吗? If it's the latter, then use a char array & do it all yourself. 如果是后者,那么使用char数组并自己完成。 It will be much faster since you can do it in one pass. 它会快得多,因为你可以一次完成它。

Once it works (comment noted above), the simplest way to speed it up is to perform the replacements using a StringBuffer . 一旦它起作用(上面的注释),加速它的最简单方法是使用StringBuffer执行替换。

But , have you measured this ? 但是 ,你测量过这个吗? Is it a bottleneck ? 这是一个瓶颈吗? I would suggest you do this before expending energy on optimisations. 我建议你在优化之前花费精力来做这件事。

hm can't you just use 嗯,你不能只是使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM