|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) |
| 4 | + |
| 5 | +require 'benchmark' |
| 6 | +require 'ruby-enum' |
| 7 | + |
| 8 | +## |
| 9 | +# Base enum, no inheritance. |
| 10 | +class Colors |
| 11 | + include Ruby::Enum |
| 12 | + |
| 13 | + define :RED, 'red' |
| 14 | + define :GREEN, 'green' |
| 15 | +end |
| 16 | + |
| 17 | +## |
| 18 | +# Subclass, adds its own enum on top of an inherited one (1 level). |
| 19 | +class SubColors < Colors |
| 20 | + define :BLUE, 'blue' |
| 21 | +end |
| 22 | + |
| 23 | +## |
| 24 | +# Sub-subclass, adds its own enum on top of 2 inherited levels. |
| 25 | +class SubSubColors < SubColors |
| 26 | + define :YELLOW, 'yellow' |
| 27 | +end |
| 28 | + |
| 29 | +n = 1_000_000 |
| 30 | + |
| 31 | +def benchmark(label, iterations, &block) |
| 32 | + time = Benchmark.realtime { iterations.times(&block) } |
| 33 | + puts "#{label}: #{time.round(4)}" |
| 34 | + time |
| 35 | +end |
| 36 | + |
| 37 | +puts "Running #{n} iterations of each scenario below\n\n" |
| 38 | + |
| 39 | +puts '--- .value lookups, by depth of inheritance ---' |
| 40 | +base_value = benchmark('base class (no inheritance)', n) { Colors.value(:RED) } |
| 41 | +sub_value = benchmark('subclass (1 level)', n) { SubColors.value(:RED) } |
| 42 | +sub_sub_value = benchmark('sub-subclass (2 levels)', n) { SubSubColors.value(:RED) } |
| 43 | + |
| 44 | +puts "\n--- Other methods on a subclass (1 level) ---" |
| 45 | +benchmark('.keys', n) { SubColors.keys } |
| 46 | +benchmark('.key?', n) { SubColors.key?(:RED) } |
| 47 | +benchmark('.to_h', n) { SubColors.to_h } |
| 48 | +count = 0 |
| 49 | +benchmark('.each', n) { SubColors.each { |_k, _v| count += 1 } } |
| 50 | + |
| 51 | +puts "\n--- Comparison ---" |
| 52 | +puts "subclass value is #{(sub_value / base_value).round(2)}x base class value" |
| 53 | +puts "sub-subclass value is #{(sub_sub_value / base_value).round(2)}x base class value" |
0 commit comments