gpt4 book ai didi

c - 为什么 Ruby 1.8.7 中的 Symbol#to_proc 变慢了?

转载 作者:数据小太阳 更新时间:2023-10-29 07:22:43 24 4
gpt4 key购买 nike

Relative Performance of Symbol#to_proc in Popular Ruby Implementations声明在 MRI Ruby 1.8.7 中,Symbol#to_proc 在其基准测试中比替代方案慢 30% 到 130%,但在 YARV Ruby 1.9.2 中并非如此。

为什么会这样? 1.8.7 的创建者没有用纯 Ruby 编写 Symbol#to_proc

此外,是否有任何 gem 可以为 1.8 提供更快的 Symbol#to_proc 性能?

(符号#to_proc 在我使用 ruby​​-prof 时开始出现,所以我不认为我犯了过早优化的罪)

最佳答案

1.8.7 中的to_proc 实现如下所示(参见object.c):

static VALUE
sym_to_proc(VALUE sym)
{
return rb_proc_new(sym_call, (VALUE)SYM2ID(sym));
}

而 1.9.2 实现(参见 string.c)如下所示:

static VALUE
sym_to_proc(VALUE sym)
{
static VALUE sym_proc_cache = Qfalse;
enum {SYM_PROC_CACHE_SIZE = 67};
VALUE proc;
long id, index;
VALUE *aryp;

if (!sym_proc_cache) {
sym_proc_cache = rb_ary_tmp_new(SYM_PROC_CACHE_SIZE * 2);
rb_gc_register_mark_object(sym_proc_cache);
rb_ary_store(sym_proc_cache, SYM_PROC_CACHE_SIZE*2 - 1, Qnil);
}

id = SYM2ID(sym);
index = (id % SYM_PROC_CACHE_SIZE) << 1;

aryp = RARRAY_PTR(sym_proc_cache);
if (aryp[index] == sym) {
return aryp[index + 1];
}
else {
proc = rb_proc_new(sym_call, (VALUE)id);
aryp[index] = sym;
aryp[index + 1] = proc;
return proc;
}
}

如果您剥离所有初始化 sym_proc_cache 的繁琐工作,那么您将(或多或少)剩下这个:

aryp = RARRAY_PTR(sym_proc_cache);
if (aryp[index] == sym) {
return aryp[index + 1];
}
else {
proc = rb_proc_new(sym_call, (VALUE)id);
aryp[index] = sym;
aryp[index + 1] = proc;
return proc;
}

所以真正的区别是 1.9.2 的 to_proc 缓存生成的 Proc,而 1.8.7 每次调用 to_proc 时都会生成一个全新的 Proc。除非每次迭代都在单独的过程中完成,否则这两者之间的性能差异将被您所做的任何基准测试放大;但是,每个流程的一次迭代会掩盖您尝试用启动成本进行基准测试的内容。

rb_proc_new 的内容看起来几乎相同(参见 1.8.7 的 eval.c 或 1.9.2 的 proc.c ) 但 1.9.2 可能会从 rb_iterate 中的任何性能改进中略微受益。缓存可能是最大的性能差异。

值得注意的是,symbol-to-hash 缓存是固定大小的(67 个条目,但我不确定 67 是从哪里来的,可能与 symbol-to 常用的运算符数量有关-proc 转换):

id = SYM2ID(sym);
index = (id % SYM_PROC_CACHE_SIZE) << 1;
/* ... */
if (aryp[index] == sym) {

如果您使用超过 67 个符号作为 proc,或者如果您的符号 ID 重叠(mod 67),那么您将无法获得缓存的全部好处。

Rails 和 1.9 编程风格涉及很多简写形式,例如:

    id = SYM2ID(sym);
index = (id % SYM_PROC_CACHE_SIZE) << 1;

而不是更长的显式 block 形式:

ints = strings.collect { |s| s.to_i }
sum = ints.inject(0) { |s,i| s += i }

鉴于这种(流行的)编程风格,通过缓存查找来以内存换取速度是有意义的。

您不太可能从 gem 获得更快的实现,因为 gem 必须替换一部分核心 Ruby 功能。不过,您可以将 1.9.2 缓存修补到 1.8.7 源代码中。

关于c - 为什么 Ruby 1.8.7 中的 Symbol#to_proc 变慢了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6501030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com