簡體   English   中英

使用僅使用單個代碼行的表示法將多個元素分配給數組的時間復雜度是多少?

[英]What is the time complexity of assigning multiple elements to the array using the notation that uses only a single code line?

我指的是這樣的東西:

int[] array = {1, 2 , 3, 4, 5};

為每個數組索引賦值是“全部在一行代碼中”完成的。

我真的不確定這在后台發生了什么,但我想象的是它類似於遍歷數組中的每個索引,然后將輸入的 int 分配給該索引:

for (int i = 0; i<array.length; i++){
array[i] = <given input>  //for array[1] the value will be 1, array[2] is 2 and so on...
}

如果是這樣的話,它在 O(n) 中對嗎? 不過,這只是我對數組的多重賦值是如何發生的假設。

非常相關,所以請查看: Java:聲明大小為 n 的數組的大 O 時間是多少?

用於初始化數組的最終字節碼涉及newarray指令,它是O(n) ,因為每個元素都先初始化為默認值 state。 請參閱: JVM 規格。 , 第 576 頁:

[...] 新數組的每個元素都被初始化為數組類型的元素類型的默認初始值(§2.3,§2.4)。

您在這里另外使用的是一個數組初始化器,所以讓我們檢查一下字節碼:

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2 , 3, 4, 5};
    }
}

...編譯為...

public class Main {
  public Main();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: iconst_5
       1: newarray       int
       3: dup
       4: iconst_0
       5: iconst_1
       6: iastore
       7: dup
       8: iconst_1
       9: iconst_2
      10: iastore
      11: dup
      12: iconst_2
      13: iconst_3
      14: iastore
      15: dup
      16: iconst_3
      17: iconst_4
      18: iastore
      19: dup
      20: iconst_4
      21: iconst_5
      22: iastore
      23: astore_1
      24: return
}

注意傳遞給它的帶有newarray的新iconst_5 這屬於代碼的“ new int[5]部分”,其中iconst_5只是5 (“整數常量 5”)。 忽略dupastore_1 ,它們對問題來說並不那么重要。

請注意iconst_0iconst_1iastore塊,它對其他 integer 常量重復。 iastore是在數組中存儲值的指令,其中第一個參數是索引,第二個參數是值。 iastore之前的兩行是 arguments。所以您看到的是字節碼讀取數組初始值設定項中的每個元素並將其存儲在數組中。

所以 one-liner 所做的實際上與此非常相似(或等效):

public class Main {
    public static void main(String[] args) {
        int[] array = new int[5];
        array[0] = 1;
        array[1] = 2;
        array[2] = 3;
        array[3] = 4;
        array[4] = 5;
    }
}

如您所見,您顯示的單行代碼實際上是字節碼級的2 * O(n)

@akuzminykh 的回答很好而且足夠了。

但是您要釣魚的是編譯時數據准備。

static final String STR = "....very long string ...";

該字符串在 class 的常量池中編譯為 UTF-8 字符串。java 字符串通常將其數據保存為 UTF-16(2 字節)字符數組,但最新的 java 版本可以保存字節數組以及編碼它。 所以假設我們的字符串常量就是這種情況。

然后仍然需要復制字節。 因此對於n個字節仍然是O(n) 但它會很快並且(可能)在本機代碼方面。 1 個字符的字符串將比 10 000 個字符的字符串加載得更快。 但真正的效果可能無法衡量,也不適合優化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM