【发布时间】:2011-06-08 16:38:40
【问题描述】:
我正在学习“中级 Perl”,它非常酷。我刚刚完成了关于“施瓦茨变换”的部分,在它沉没之后,我开始想知道为什么变换不使用缓存。在具有多个重复值的列表中,转换会重新计算每个值的值,所以我想为什么不使用哈希来缓存结果。这是一些代码:
# a place to keep our results
my %cache;
# the transformation we are interested in
sub foo {
# expensive operations
}
# some data
my @unsorted_list = ....;
# sorting with the help of the cache
my @sorted_list = sort {
($cache{$a} //= &foo($a)) <=> ($cache{$b} //= &foo($b))
} @unsorted_list;
我错过了什么吗?为什么没有在书籍中列出缓存版本的 Schwartzian 变换,并且通常只是更好地传播,因为乍一看我认为缓存版本应该更有效?
编辑:daxim 在 cmets 中指出这被称为orcish maneuver。所以我并没有发疯,虽然我不太了解这个名字。
【问题讨论】:
-
@daxim:哈哈,就是这样。我只是不知道这个名字。
-
Orcish 是 Or Cache 的损坏。
标签: perl caching optimization sorting memoization