문제

Is using my %data; below okay or should I switch to my $data={}; ?

#!/usr/bin/perl -wT
use strict;
use JSON;

sub makeJson {
        my %data;

        $data{kib} = 1;
        $data{games} = {
                0 => [],
                1 => [qw(a b c d e)],
        };

        return \%data;
}

my $x = makeJson();
print encode_json($x) . "\n";

I'm confused because -

If the makeJson() is called several times - and the my %data; is allocated at stack and then that address is being returned - wouldn't that be a memory leak or maybe not a "leak", but a "problem"? Because there would be memory allocated at the stack, which is still referenced and thus can not be deallocated.

And other way around: if I have a subroutine returning a hash reference, which is better to use my %data; (faster, because preallocated by compiler?) or my $data={}; ?

도움이 되었습니까?

해결책

Perl is not C.

That's the actual answer to your question, but I'll expand a bit.

Perl is not C in that Perl does not have automatic variables. It has lexical and dynamic variables and that's it.

Perl is not C in that Perl does memory management so you (mostly) don't have to. Absent circular references, memory leaks don't occur.

Perl is not C in that the cost of being an interpreted language dominates most performance calculations, and so micro-optimizing hashes versus hashrefs is almost always irrelevant.

Use whichever construct more naturally expresses your intention. Neither leaks memory more than the other; Amdahl can worry about the tiny performance differences. Perl is not C.

다른 팁

Perl (and a lot other interpreted languages) does not have the concept of a stack like compiled languages. It has scoping rules instead. Therefore Perl is able to ensure that you get no memory leaks.

Indeed even if it had the same concept of the stack it would just be returning an address that becomes invalid.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top