Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is == faster than eql?
    text
    copied!<p>I read in the documentation for the String class that <code>eql?</code> is a strict equality operator, without type conversion, and <code>==</code> is a equality operator which tries to convert second its argument to a String, and, the C source code for this methods confirms that:</p> <p>The <code>eql?</code> source code:</p> <pre><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></pre> <p>The <code>==</code> source code:</p> <pre><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></pre> <p>But when I tried to benchmark these methods, I was suprised that <code>==</code> is faster than <code>eql?</code> by up to 20%! My benchmark code is:</p> <pre><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></pre> <p>And results:</p> <p>Ruby 1.9.3-p125:</p> <pre><code>26.420000 0.250000 26.670000 ( 26.820762) 21.520000 0.200000 21.720000 ( 21.843723) </code></pre> <p>Ruby 1.9.2-p290:</p> <pre><code>25.930000 0.280000 26.210000 ( 26.318998) 19.800000 0.130000 19.930000 ( 19.991929) </code></pre> <p>So, can anyone explain why the more simple <code>eql?</code> method is slower than <code>==</code> method in the case when I run it for two similar strings?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload