繁体   English   中英

Java 的 substring() 的时间复杂度

[英]Time complexity of Java's substring()

Java 中String#substring()方法的时间复杂度是多少?

新答案

从 Java 7 生命周期中的更新 6 开始, substring的行为已更改为创建副本 - 因此,据我所知,每个String引用一个与任何其他对象共享的char[] 所以在这一点上, substring()变成了一个 O(n) 操作,其中 n 是子字符串中的数字。

旧答案:Java 7 之前的版本

未记录 - 但实际上 O(1) 如果您假设不需要垃圾收集等。

它只是构建一个新的String对象,该对象引用相同的底层char[]但具有不同的偏移量和计数值。 所以成本是执行验证和构建一个新的(相当小的)对象所花费的时间。 这是 O(1) 就讨论操作的复杂性而言是明智的.

在旧版本的 Java 中它是 O(1) - 正如 Jon 所说,它只是创建了一个具有相同底层 char[] 和不同偏移量和长度的新字符串。

然而,这实际上从 Java 7 更新 6 开始发生了变化。

消除了 char[] 共享,并删除了偏移量和长度字段。 substring() 现在只是将所有字符复制到一个新的字符串中。

因此,子字符串在 Java 7 更新 6 中是 O(n)

现在是线性复杂度。 这是在修复子字符串的内存泄漏问题之后。

因此,从 Java 1.7.0_06 开始,请记住 String.substring 现在具有线性复杂度而不是常量。

为乔恩的回答添加证据。 我有同样的疑问,想检查字符串的长度是否对子字符串函数有任何影响。 编写以下代码来检查子字符串实际依赖于哪个参数。

import org.apache.commons.lang.RandomStringUtils;

public class Dummy {

    private static final String pool[] = new String[3];
    private static int substringLength;

    public static void main(String args[]) {
        pool[0] = RandomStringUtils.random(2000);
        pool[1] = RandomStringUtils.random(10000);
        pool[2] = RandomStringUtils.random(100000);
        test(10);
        test(100);
        test(1000);
    }

    public static void test(int val) {
        substringLength = val;
        StatsCopy statsCopy[] = new StatsCopy[3];
        for (int j = 0; j < 3; j++) {
            statsCopy[j] = new StatsCopy();
        }
        long latency[] = new long[3];
        for (int i = 0; i < 10000; i++) {
            for (int j = 0; j < 3; j++) {
                latency[j] = latency(pool[j]);
                statsCopy[j].send(latency[j]);
            }
        }
        for (int i = 0; i < 3; i++) {
            System.out.println(
                    " Avg: "
                            + (int) statsCopy[i].getAvg()
                            + "\t String length: "
                            + pool[i].length()
                            + "\tSubstring Length: "
                            + substringLength);
        }
        System.out.println();
    }

    private static long latency(String a) {
        long startTime = System.nanoTime();
        a.substring(0, substringLength);
        long endtime = System.nanoTime();
        return endtime - startTime;
    }

    private static class StatsCopy {
        private  long count = 0;
        private  long min = Integer.MAX_VALUE;
        private  long max = 0;
        private  double avg = 0;

        public  void send(long latency) {
            computeStats(latency);
            count++;
        }

        private  void computeStats(long latency) {
            if (min > latency) min = latency;
            if (max < latency) max = latency;
            avg = ((float) count / (count + 1)) * avg + (float) latency / (count + 1);
        }

        public  double getAvg() {
            return avg;
        }

        public  long getMin() {
            return min;
        }

        public  long getMax() {
            return max;
        }

        public  long getCount() {
            return count;
        }
    }

}

在 Java 8 中执行的输出是:

 Avg: 128    String length: 2000    Substring Length: 10
 Avg: 127    String length: 10000   Substring Length: 10
 Avg: 124    String length: 100000  Substring Length: 10

 Avg: 172    String length: 2000    Substring Length: 100
 Avg: 175    String length: 10000   Substring Length: 100
 Avg: 177    String length: 100000  Substring Length: 100

 Avg: 1199   String length: 2000    Substring Length: 1000
 Avg: 1186   String length: 10000   Substring Length: 1000
 Avg: 1339   String length: 100000  Substring Length: 1000

证明子串函数取决于请求的子串的长度而不是串的长度。

O(1) 因为没有复制原始字符串,它只是创建一个具有不同偏移信息的新包装器对象。

从下面的内容中自行判断,但 Java 的性能缺陷在于其他地方,而不是字符串的子字符串。 代码:

public static void main(String[] args) throws IOException {

        String longStr = "asjf97zcv.1jm2497z20`1829182oqiwure92874nvcxz,nvz.,xo" + 
                "aihf[oiefjkas';./.,z][p\\°°°°°°°°?!(*#&(@*&#!)^(*&(*&)(*&" +
                "fasdznmcxzvvcxz,vc,mvczvcz,mvcz,mcvcxvc,mvcxcvcxvcxvcxvcx";
        int[] indices = new int[32 * 1024];
        int[] lengths = new int[indices.length];
        Random r = new Random();
        final int minLength = 6;
        for (int i = 0; i < indices.length; ++i)
        {
            indices[i] = r.nextInt(longStr.length() - minLength);
            lengths[i] = minLength + r.nextInt(longStr.length() - indices[i] - minLength);
        }

        long start = System.nanoTime();

        int avoidOptimization = 0;
        for (int i = 0; i < indices.length; ++i)
            //avoidOptimization += lengths[i]; //tested - this was cheap
            avoidOptimization += longStr.substring(indices[i],
                    indices[i] + lengths[i]).length();

        long end = System.nanoTime();
        System.out.println("substring " + indices.length + " times");
        System.out.println("Sum of lengths of splits = " + avoidOptimization);
        System.out.println("Elapsed " + (end - start) / 1.0e6 + " ms");
    }

输出:

substring 32768 times
Sum of lengths of splits = 1494414
Elapsed 2.446679 ms

是否为 O(1) 取决于。 如果你只是在内存中引用相同的字符串,那么想象一下长的字符串,你制作子字符串并停止引用长字符串。 长时间释放内存不是很好吗?

Java 1.7.0_06之前:O(1)。

Java 1.7.0_06 之后:O(n)。 由于内存泄漏,这已更改。 从 String 中删除字段offsetcount后,子字符串实现变为 O(n)。

更多详情请参考: http : //java-performance.info/changes-to-string-java-1-7-0_06/

暂无
暂无

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

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