How to compile Ruby?

后端 未结 7 1960
青春惊慌失措
青春惊慌失措 2020-12-13 14:22

Is there a tool that can allow me to compile Ruby code so that it runs somewhat faster?

For example, I have heard that there is a tool for Python called \"pyc\" tha

7条回答
  •  春和景丽
    2020-12-13 14:44

    From ruby 2.3.0 its so easy to compile your source code to bytecodes that the Ruby-VM understands.

    byte_code = RubyVM::InstructionSequence.compile_file '/home/john/somefile.rb'
    
    File.binwrite '/home/john/bytecode', byte_code.to_binary
    

    and in Command Line

    $ cat bytecode 
    
    YARB�
    IUsx86_64-linux*.*1
    
    +1�!AA*1
    !qy��������yyQ� E/home/john/somefile.rbE
    E EshivaEhelloEAEputsEcore#define_methodu����� 5M

    The content of the file

    class A
      def shiva
        puts 'hello'
      end
    end
    

    What is the purpose?

    Well, ruby takes time to compile your source code into byte codes so you can load your bytecodes directly into ruby and execute. No overhead of grammar checking and compilation. It much faster than normal processes.

    How to load byte code?

    bytecode = File.binread('/home/john/bytecode')
    instruction_from_byte_code = RubyVM::InstructionSequence.load_from_binary bytecode
    
    instruction_from_byte_code.eval
    # => :shiva
    

    Note: This answer is tested in MRI only. It might or might not work in other Ruby Implementations

提交回复
热议问题