gpt4 book ai didi

java - 为什么大绳子增加长度似乎需要花费更多? string.length 的复杂度是多少?

转载 作者:行者123 更新时间:2023-12-02 12:57:47 25 4
gpt4 key购买 nike

根据time complexity or hidden cost of <Array Name>.length in java ,在java中数组获取长度是O(1)的操作。由于String是一个char数组,我认为它是相同的。

但是当我做一个简单的测试时:

public static void main(String args[]) {
String a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
for (int i = 0; i < 23; i++){
long start = System.nanoTime();
int l = a.length();
long end = System.nanoTime();
System.out.println("length: " + l + " cost: " + String.valueOf(end - start));
a = a + a;
}
}

然后得到

length: 100 cost: 395
length: 200 cost: 395
length: 400 cost: 395
length: 800 cost: 394
length: 1600 cost: 395
length: 3200 cost: 394
length: 6400 cost: 395
length: 12800 cost: 394
length: 25600 cost: 394
length: 51200 cost: 395
length: 102400 cost: 789
length: 204800 cost: 789
length: 409600 cost: 1974
length: 819200 cost: 790
length: 1638400 cost: 3158
length: 3276800 cost: 3553
length: 6553600 cost: 4342
length: 13107200 cost: 3552
length: 26214400 cost: 2368
length: 52428800 cost: 6711
length: 104857600 cost: 3158
length: 209715200 cost: 1974

当超过400000个字符时,长度操作成本似乎要高得多。

我是否错过或误解了什么?

最佳答案

String.length() 确实是 O(1)。如果您查看该类(自 Java 1.6 起可用),它会返回一个字段

public int length() {
return value.length;
}

所以我想说你的基准测试技术一定会引入错误。

关于java - 为什么大绳子增加长度似乎需要花费更多? string.length 的复杂度是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44368218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com