如何在 Ruby C API 中有效地合并两个哈希值?
我正在为 Ruby 编写一个 C 扩展,它确实需要合并两个哈希值,但是 rb_hash_merge() 函数在 Ruby 1.8.6 中是静态的。 我尝试改为使用:
rb_funcall(hash1, rb_intern("merge"), 1, hash2);
但这太慢了,并且在此应用程序中性能非常关键。
有谁知道如何在考虑到效率和速度的情况下执行此合并?
(请注意,我尝试简单地查看 rb_hash_merge() 的源代码并复制它,但它充满了其他静态函数,这些函数本身也充满了更多静态函数,因此似乎几乎不可能解开......我需要另一种方法)
I am writing a C extension for Ruby that really needs to merge two hashes, however the rb_hash_merge() function is STATIC in Ruby 1.8.6. I have tried instead to use:
rb_funcall(hash1, rb_intern("merge"), 1, hash2);
but this is much too slow, and performance is very critical in this application.
Does anyone know how to go about performing this merge with efficiency and speed in mind?
(Note I have tried simply looking at the source for rb_hash_merge() and replicating it but it is RIDDLED with other static functions, which are themselves riddled with yet more static functions so it seems almost impossible to disentangle...i need another way)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,看起来可能无法在已发布的 API 中进行优化。
测试代码:
现在是测试结果:
所以看起来我们可以在 0.2 秒的操作上最多减少约 0.004 秒。
鉴于除了设置值之外可能没有那么多,因此可能没有那么多空间进行进一步优化。 也许尝试破解 ruby 源代码本身 - 但那时您不再真正开发“扩展”,而是更改语言,因此它可能行不通。
如果散列连接是您需要在 C 部分中多次执行的操作 - 那么可能使用内部数据结构并仅在最后一遍将它们导出到 Ruby 散列中将是优化事物的唯一方法。
ps 代码的初始框架借自这个优秀的教程< /a>
Ok, looks like might be not possible to optimize within the published API.
Test code:
Now the test results:
So it looks like we might shave off at maximum ~0.004s on a 0.2s operation.
Given that there's probably not that much besides setting the values, there might not be that much space for further optimizations. Maybe try to hack the ruby source itself - but at that point you no longer really develop "extension" but rather change the language, so it probably won't work.
If the join of hashes is something that you need to do many times in the C part - then probably using the internal data structures and only exporting them into Ruby hash in the final pass would be the only way of optimizing things.
p.s. The initial skeleton for the code borrowed from this excellent tutorial