From a7c38126f8a67fb72a3b0aee1c50335fdeffd9b4 Mon Sep 17 00:00:00 2001 From: Adrian Setyadi Date: Tue, 13 Feb 2018 17:48:17 +0700 Subject: [PATCH] Add inheritance check --- README.md | 17 ++++++++++++++ code/general/inheritance-check.rb | 38 +++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 code/general/inheritance-check.rb diff --git a/README.md b/README.md index 8c36bf1..e460174 100644 --- a/README.md +++ b/README.md @@ -188,6 +188,23 @@ Comparison: Kernel loop: 0.2 i/s - 2.41x slower ``` +##### `ancestors.include?` vs `<=` [code](code/general/inheritance-check.rb) + +``` +$ ruby -vW0 code/general/inheritance-check.rb +ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-linux] +Warming up -------------------------------------- + less than or equal 66.992k i/100ms + ancestors.include? 16.943k i/100ms +Calculating ------------------------------------- + less than or equal 1.250M (± 6.4%) i/s - 6.230M in 5.006896s + ancestors.include? 192.603k (± 4.8%) i/s - 965.751k in 5.025917s + +Comparison: + less than or equal: 1249606.0 i/s + ancestors.include?: 192602.9 i/s - 6.49x slower +``` + #### Method Invocation ##### `call` vs `send` vs `method_missing` [code](code/method/call-vs-send-vs-method_missing.rb) diff --git a/code/general/inheritance-check.rb b/code/general/inheritance-check.rb new file mode 100644 index 0000000..2c27221 --- /dev/null +++ b/code/general/inheritance-check.rb @@ -0,0 +1,38 @@ +require 'benchmark/ips' + +# You may ask: 'Is there a project that still using `ancestors.include?`?' +# By quick searching, I found the following popular repositories are still using it: +# - rake +# - https://github.com/ruby/rake/blob/7d0c08fe4e97083a92d2c8fc740cb421fd062117/lib/rake/task_manager.rb#L28 +# - warden +# - https://github.com/hassox/warden/blob/090ed153dbd2f5bf4a1ca672b3018877e21223a4/lib/warden/strategies.rb#L16 +# - metasploit-framework +# - https://github.com/rapid7/metasploit-framework/blob/cac890a797d0d770260074dfe703eb5cfb63bd46/lib/msf/core/payload_set.rb#L239 +# - https://github.com/rapid7/metasploit-framework/blob/cb82015c8782280d964e222615b54c881bd36bbe/lib/msf/core/exploit.rb#L1440 +# - hanami +# - https://github.com/hanami/hanami/blob/506a35e5262939eb4dce9195ade3268e19928d00/lib/hanami/components/routes_inspector.rb#L54 +# - https://github.com/hanami/hanami/blob/aec069b602c772e279aa0a7f48d1a04d01756ee3/lib/hanami/configuration.rb#L114 +raise unless Object.ancestors.include?(Kernel) +raise unless (Object <= Kernel) + +def fast + (Class <= Class) + (Class <= Module) + (Class <= Object) + (Class <= Kernel) + (Class <= BasicObject) +end + +def slow + Class.ancestors.include?(Class) + Class.ancestors.include?(Module) + Class.ancestors.include?(Object) + Class.ancestors.include?(Kernel) + Class.ancestors.include?(BasicObject) +end + +Benchmark.ips do |x| + x.report('less than or equal') { fast } + x.report('ancestors.include?') { slow } + x.compare! +end