charat()还是子字符串?哪个更快?

2exbekwf  于 2021-06-30  发布在  Java
关注(0)|答案(6)|浏览(184)

我想遍历字符串中的每个字符,并将字符串中的每个字符作为字符串传递给另一个函数。

String s = "abcdefg";
for(int i = 0; i < s.length(); i++){
    newFunction(s.substring(i, i+1));}

String s = "abcdefg";
for(int i = 0; i < s.length(); i++){
    newFunction(Character.toString(s.charAt(i)));}

最终结果必须是字符串。那么,有什么办法能更快更有效呢?

xoefb8l8

xoefb8l81#

和往常一样:这没关系,但是如果你坚持花时间在微观优化上,或者如果你真的喜欢为你非常特殊的用例进行优化,那么试试这个:

import org.junit.Assert;
import org.junit.Test;

public class StringCharTest {

    // Times:
    // 1. Initialization of "s" outside the loop
    // 2. Init of "s" inside the loop
    // 3. newFunction() actually checks the string length,
    // so the function will not be optimized away by the hotstop compiler

    @Test
    // Fastest: 237ms / 562ms / 2434ms
    public void testCacheStrings() throws Exception {
        // Cache all possible Char strings
        String[] char2string = new String[Character.MAX_VALUE];
        for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) {
            char2string[i] = Character.toString(i);
        }

        for (int x = 0; x < 10000000; x++) {
            char[] s = "abcdefg".toCharArray();
            for (int i = 0; i < s.length; i++) {
                newFunction(char2string[s[i]]);
            }
        }
    }

    @Test
    // Fast: 1687ms / 1725ms / 3382ms
    public void testCharToString() throws Exception {
        for (int x = 0; x < 10000000; x++) {
            String s = "abcdefg";
            for (int i = 0; i < s.length(); i++) {
                // Fast: Creates new String objects, but does not copy an array
                newFunction(Character.toString(s.charAt(i)));
            }
        }
    }

    @Test
    // Very fast: 1331 ms/ 1414ms / 3190ms
    public void testSubstring() throws Exception {
        for (int x = 0; x < 10000000; x++) {
            String s = "abcdefg";
            for (int i = 0; i < s.length(); i++) {
                // The fastest! Reuses the internal char array
                newFunction(s.substring(i, i + 1));
            }
        }
    }

    @Test
    // Slowest: 2525ms / 2961ms / 4703ms
    public void testNewString() throws Exception {
        char[] value = new char[1];
        for (int x = 0; x < 10000000; x++) {
            char[] s = "abcdefg".toCharArray();
            for (int i = 0; i < s.length; i++) {
                value[0] = s[i];
                // Slow! Copies the array
                newFunction(new String(value));
            }
        }
    }

    private void newFunction(String string) {
        // Do something with the one-character string
        Assert.assertEquals(1, string.length());
    }

}
6ovsh4lw

6ovsh4lw2#

leetcode似乎更喜欢这里的substring选项。
我就是这样解决这个问题的:

class Solution {
public int strStr(String haystack, String needle) {
    if(needle.length() == 0) {
        return 0;
    }

    if(haystack.length() == 0) {
        return -1;
    }

    for(int i=0; i<=haystack.length()-needle.length(); i++) {
        int count = 0;
        for(int j=0; j<needle.length(); j++) {
            if(haystack.charAt(i+j) == needle.charAt(j)) {
                count++;
            }
        }
        if(count == needle.length()) {
            return i;
        }
    }
    return -1;
}

}
这是他们给出的最佳解决方案:

class Solution {
public int strStr(String haystack, String needle) {
    int length;
    int n=needle.length();
    int h=haystack.length();
    if(n==0)
        return 0;
    // if(n==h)
    //     length = h;
    // else
        length = h-n;
    if(h==n && haystack.charAt(0)!=needle.charAt(0))
            return -1;
    for(int i=0; i<=length; i++){
        if(haystack.substring(i, i+needle.length()).equals(needle))
            return i;
    }
    return -1;
}

}
老实说,我不明白这有什么关系。

lfapxunr

lfapxunr3#

我将首先使用string.tochararray()从源字符串获取基础char[],然后继续调用newfunction。
但是我同意jesper的观点,如果你能处理字符,避免所有的字符串函数,那就最好了。。。

z9smfwbn

z9smfwbn4#

答案是:没关系。
分析你的代码。这是你的瓶颈吗?

yh2wf1be

yh2wf1be5#

newFunction 真的需要休息一下 String ? 如果你能 newFunction 拿一个 char 并这样称呼它:

newFunction(s.charAt(i));

这样可以避免创建临时字符串对象。
回答你的问题:很难说哪一个更有效率。在这两个例子中 String 必须创建只包含一个字符的对象。哪个更有效取决于 String.substring(...) 以及 Character.toString(...) 在特定的java实现上实现。找到它的唯一方法是通过探查器运行您的程序,并查看哪个版本使用更多的cpu和/或内存。通常情况下,您不应该担心这样的微优化—只有当您发现这是性能和/或内存问题的原因时,才应该花时间在这方面。

qzwqbdag

qzwqbdag6#

在你发布的两个片段中,我不想说。我同意威尔的观点,即它几乎肯定与代码的整体性能无关——如果不是这样,您只需进行更改,并自行确定在硬件上使用jvm时哪个数据最快。
也就是说,如果您首先将字符串转换为char数组,然后对数组执行迭代,那么第二个代码段可能会更好。这样做只会执行一次字符串开销(转换为数组),而不是每次调用。此外,还可以使用一些索引将数组直接传递给字符串构造函数,这比从数组中取出一个字符来单独传递(然后将其转换为一个字符数组)更有效:

String s = "abcdefg";
char[] chars = s.toCharArray();
for(int i = 0; i < chars.length; i++) {
    newFunction(String.valueOf(chars, i, 1));
}

但为了强调我的第一点,当你看到你在每一次通话中实际上都在回避什么的时候 String.charAt() -它是两个边界检查,一个(懒惰的)布尔或,和一个加法。这不会有任何明显的区别。字符串构造函数中的差异也不存在。
从本质上讲,这两种习惯用法在性能方面都很好(这两种习惯用法都没有明显的低效),因此您不应该再花时间处理它们,除非探查器显示这会占用大量应用程序的运行时。即使这样,您也几乎可以肯定地通过重组此领域的支持代码(例如 newFunction 把整根绳子都拿走);在这一点上,java.lang.string得到了很好的优化。

相关问题