What is the purpose of CONST_ID () in ruby โ€‹โ€‹and what are the advantages over rb_intern ()?

In c extensions for ruby, to call a method you can do

rb_funcall(object, rb_intern("method name"), argumentcount, arg1, arg2, โ€ฆ); 

where rb_intern () returns some internal representation of the method name. I saw some code that does instead

 ID method; CONST_ID(method, "method name"); rb_funcall(object, method, argumentcount, arg1, arg2, โ€ฆ); 

What exactly is the difference between rb_intern () and CONST_ID. What are the benefits of CONST_ID ()?

+4
source share
1 answer

The CONST_ID macro calls rb_intern2 (which is about the same as rb_intern ) to get the identifier, but there is one big difference. If you look at the source of the CONST_ID macro in include/ruby/ruby.h , you will see that it starts a new block and defines a static ID variable to cache the result. If the next time this block is executed, the static variable is already set, it simply returns the result of caching instead of searching for the ID again and again.

This way they do the same, but CONST_ID should be faster for multiple searches of the same string.

+4
source

Source: https://habr.com/ru/post/1380943/


All Articles