我应该返回引用还是哈希值?

发布于 2024-10-31 05:02:48 字数 642 浏览 0 评论 0原文

可能的重复:
从 Perl 子例程返回整个数组是否效率低下?< /a>

我有这段代码

my $h = function($ref);

sub function {
    my $ref = shift @_;

    my %HoA = ();

    foreach my $key (keys %$ref) {
        $HoA{$key} = 1;
    }

    return \%HoA;

}

,它返回对 %HoA 的引用。

就性能和内存使用而言,最好返回引用还是应该返回 %HoA

Possible Duplicate:
Is returning a whole array from a Perl subroutine inefficient?

I have this code

my $h = function($ref);

sub function {
    my $ref = shift @_;

    my %HoA = ();

    foreach my $key (keys %$ref) {
        $HoA{$key} = 1;
    }

    return \%HoA;

}

which returns a reference to %HoA.

In terms of performance and memory usage, is it best to return a reference or should I return %HoA ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

两人的回忆 2024-11-07 05:02:48

如果您返回 %HoA,您将按其值返回哈希值,因此它将被复制并占用额外的内存。如果通过引用返回它,它将不会被复制,因此在性能和内存方面会更好。

顺便说一句,我认为如果您返回 %HoA 那么它将被垃圾收集器销毁,因为它不会有任何引用。

If you return %HoA you return hash by its value, so it would be copied and takes additional memory. If you return it by reference it wouldn't be copied, so it's better in terms of performance and memory.

BTW, I think if you return %HoA then it will be destroyed by garbage collector because there wouldn't be any references on it.

゛时过境迁 2024-11-07 05:02:48

当以普通哈希形式提供哈希时,需要复制所有元素。对于非常大的哈希值,这可能是一个性能问题。当提供 hashref 时,仅复制引用。这样一般会比较快。

此外,您可能会在以下内容中找到改进代码的灵感:

#!/usr/bin/perl

my $ref = {
        foo => 23,
        bar => 42,
};

# do it with function
sub hash_to_1 {
        my $hash = shift;

        my %result;

        # list assignment like: (all hash elements) = ('1' as often as number of keys)
        @result{keys %$hash} = (1) x keys %$hash;

        return \%result;
}

# do it one line
my %new;
map { $new{$_} = 1} keys %$ref;

When providing the hash as plain hash all elements need to be copied. For really large hashes this might be a performance issue. When providing a hashref only the reference is copied. This generally faster.

Additionally you might find inspiration to improve your code in this:

#!/usr/bin/perl

my $ref = {
        foo => 23,
        bar => 42,
};

# do it with function
sub hash_to_1 {
        my $hash = shift;

        my %result;

        # list assignment like: (all hash elements) = ('1' as often as number of keys)
        @result{keys %$hash} = (1) x keys %$hash;

        return \%result;
}

# do it one line
my %new;
map { $new{$_} = 1} keys %$ref;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文