我应该返回引用还是哈希值?
可能的重复:
从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您返回 %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.
当以普通哈希形式提供哈希时,需要复制所有元素。对于非常大的哈希值,这可能是一个性能问题。当提供 hashref 时,仅复制引用。这样一般会比较快。
此外,您可能会在以下内容中找到改进代码的灵感:
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: