Rubyracer (V8 binding for Ruby) performs really slow

折月煮酒 提交于 2019-12-06 13:02:41

The problem is that by default, The Ruby Racer copies strings from Ruby to V8 and vice versa.

In your benchmark, accessing those 6 string properties will result in at least 6 memcpy() operations which must allocate the new memory and walk the length of the string byte-by-byte to move it over to the new location. Compare this with the Ruby side which is basically a no-op (the string object just wraps a pointer that has already been allocated and setup) and it's no wonder it's far slower.

You can change this behavior to pass Strings by reference rather than by value.

class Wrapper
  attr_reader :object

  def inititialize(object)
    @object = object
  end
end

cxt['aString'] = Wrapper.new('not copied')

Of course, if you want to access the string in javascript, you will have to eventually pay for the copy. You can use this wrapper technique for Nums, arrays and Hashes all of which are copied over to JavaScript by default.

see https://github.com/cowboyd/therubyracer/wiki/Converting-ruby-object-to-javascript for more details.

V8 does support the concept of externally managed strings, which would allow you to allocate a char * in Ruby, but then use its address from V8. However, this functionality is not currently available in The Ruby Racer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!