perl - array of integers using way too much memory?

后端 未结 8 688
我寻月下人不归
我寻月下人不归 2021-01-18 06:05

When I run the following script:

my @arr = [1..5000000];

for($i=0; $i<5000000; $i++) {
        $arr[$i] = $i;
        if($i % 1000000 == 0) {
                    


        
8条回答
  •  孤街浪徒
    2021-01-18 06:16

    Complete revision of my answer. Looking at what you have in your code, I see some strange things.

    my @arr = [1..5000000];
    

    Here, you assign an anonymous array-reference to $arr[0]. This array only holds one value: The array reference. The hidden anonymous array holds the 5 million numbers.

    for($i=0; $i<5000000; $i++) {
            $arr[$i] = $i;
            if($i % 1000000 == 0) {
                    print "$i\n";
            }
    }
    

    Here, you fill the array with 5 million sequential numbers, overwriting the array reference in the declaration.

    A much shorter way to do it would be:

    my @arr = (1 .. 5_000_000);
    

    Perhaps that will save you some memory.

提交回复
热议问题