Dlaczego == szybciej niż eql?
Przeczytałem w dokumentacji klasy String, żeeql?
jest operatorem ścisłej równości, bez konwersji typu i==
jest operatorem równości, który próbuje przekonwertować swój drugi argument na String, a kod źródłowy C dla tych metod potwierdza, że:
Theeql?
kod źródłowy:
<code>static VALUE rb_str_eql(VALUE str1, VALUE str2) { if (str1 == str2) return Qtrue; if (TYPE(str2) != T_STRING) return Qfalse; return str_eql(str1, str2); } </code>
The==
kod źródłowy:
<code>VALUE rb_str_equal(VALUE str1, VALUE str2) { if (str1 == str2) return Qtrue; if (TYPE(str2) != T_STRING) { if (!rb_respond_to(str2, rb_intern("to_str"))) { return Qfalse; } return rb_equal(str2, str1); } return str_eql(str1, str2); } </code>
Ale kiedy próbowałem porównać te metody, byłem zaskoczony==
jest szybszy niżeql?
nawet o 20%! Mój kod testowy to:
<code>require "benchmark" RUN_COUNT = 100000000 first_string = "Woooooha" second_string = "Woooooha" time = Benchmark.measure do RUN_COUNT.times do |i| first_string.eql?(second_string) end end puts time time = Benchmark.measure do RUN_COUNT.times do |i| first_string == second_string end end puts time </code>
I wyniki:
Ruby 1.9.3-p125:
<code>26.420000 0.250000 26.670000 ( 26.820762) 21.520000 0.200000 21.720000 ( 21.843723) </code>
Ruby 1.9.2-p290:
<code>25.930000 0.280000 26.210000 ( 26.318998) 19.800000 0.130000 19.930000 ( 19.991929) </code>
Czy ktoś może wyjaśnić, dlaczego jest prostszyeql?
metoda jest wolniejsza niż==
metoda w przypadku, gdy uruchamiam go dla dwóch podobnych ciągów?