summaryrefslogtreecommitdiff
path: root/support/benchmarks/load.rb
blob: 91c9ae33cd11c6b8fd863aa39423df527893afa8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# -*- ruby encoding: utf-8 -*-

require 'benchmark'

module Benchmarks
  class Load
    def self.report(load_path, repeats)
      new(load_path, repeats.to_i).report
    end

    def initialize(load_path, repeats = nil)
      @cache_file = File.expand_path('../cache.mtc', __FILE__)
      @repeats    = repeats.to_i
      @repeats    = 50 if repeats <= 0
      @load_path  = load_path
    end

    def reload_mime_types(repeats = 1, options = { force_load: false, columnar: false })
      force_load = options.fetch(:force_load, false)
      columnar = options.fetch(:columnar, false)

      repeats.times {
        Object.send(:remove_const, :MIME) if defined? ::MIME
        $LOADED_FEATURES.delete_if { |n| n =~ /#{@load_path}/ }

        if columnar
          require 'mime/types/columnar'
        else
          require 'mime/types'
        end
        ::MIME::Types.send(:__types__) if force_load
      }
    end

    def report
      remove_cache

      Benchmark.bm(17) do |mark|
        mark.report("Normal:") { reload_mime_types(@repeats) }
        mark.report("Columnar:") { reload_mime_types(@repeats, columnar: true) }

        ENV['RUBY_MIME_TYPES_LAZY_LOAD'] = 'yes'
        mark.report("Lazy:") { reload_mime_types(@repeats) }
        mark.report("Lazy+Load:") { reload_mime_types(@repeats, force_load: true) }

        ENV.delete('RUBY_MIME_TYPES_LAZY_LOAD')

        ENV['RUBY_MIME_TYPES_CACHE'] = @cache_file
        reload_mime_types

        mark.report("Cached:") { reload_mime_types(@repeats) }
        ENV['RUBY_MIME_TYPES_LAZY_LOAD'] = 'yes'
        mark.report("Lazy Cached:") { reload_mime_types(@repeats) }
        mark.report("Lazy Cached Load:") { reload_mime_types(@repeats, force_load: true) }
      end
    ensure
      remove_cache
    end

    def remove_cache
      File.unlink(@cache_file) if File.exist?(@cache_file)
    end
  end
end