Guest User

Untitled

a guest
Feb 20th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. require 'merb-core'
  2. require 'merb-haml'
  3.  
  4. END {
  5. require 'rbench'
  6.  
  7. expando = Expando.new
  8.  
  9. raise "haml's not fair" unless expando.efficient_haml == expando.naive_haml
  10. raise "erb's not fair" unless expando.efficient_erb == expando.naive_erb
  11.  
  12.  
  13. # Results on my machine:
  14. # | naive | expand | naive/expand |
  15. # ---------------------------------------------------------
  16. # haml x10000 | 2.496 | 0.636 | 3.93x |
  17. # erb x10000 | 1.549 | 0.428 | 3.62x |
  18. RBench.run(10_000) do
  19. column :times
  20. column :naive, :title => "naive"
  21. column :expand, :title => "expand"
  22. column :diff, :title => "naive/expand", :compare => [:naive,:expand]
  23.  
  24. report "haml" do
  25. expand do
  26. expando.efficient_haml
  27. end
  28. naive do
  29. expando.naive_haml
  30. end
  31. end
  32.  
  33. report "erb" do
  34. expand do
  35. expando.efficient_erb
  36. end
  37. naive do
  38. expando.naive_erb
  39. end
  40. end
  41. end
  42. }
  43.  
  44.  
  45. module Templatizer
  46. module Compiled
  47. end
  48.  
  49. FakeIo = Struct.new :read, :path
  50.  
  51. def expand_template(type, string, values={})
  52. context = caller[0]
  53. mname = :"__expanded__#{context.gsub(%r{\W}, '_')}"
  54.  
  55. extend ::Templatizer::Compiled
  56. unless respond_to? mname
  57. string = string.dedent
  58.  
  59. io = FakeIo.new string, context.scan(/.*?:\d+/).first
  60. Merb::Template.engine_for(".#{type}").compile_template(io, mname, values.keys, ::Templatizer::Compiled)
  61. end
  62.  
  63. send(mname, values)
  64. end
  65. end
  66.  
  67. class Object
  68. include Templatizer
  69. end
  70.  
  71. class String
  72. def dedent
  73. min_size = Float::MAX
  74. self.scan(/^( *)\S/).each do |indentation, ignored|
  75. min_size = [min_size, indentation.length].min
  76. end
  77. self.gsub(/^ {0,#{min_size}}/, '')
  78. end
  79. end
  80.  
  81.  
  82.  
  83.  
  84. class Expando
  85. def initialize
  86. @instance = "YO"
  87. end
  88.  
  89. def efficient_haml
  90. expand_template(:haml, <<-HAML, :a => 1)
  91. = @instance
  92. = a
  93. HAML
  94. end
  95.  
  96. def naive_haml
  97. haml = Haml::Engine.new <<-EOS
  98. = @instance
  99. = a
  100. EOS
  101.  
  102. haml.render self, :a => 1
  103. end
  104.  
  105. def efficient_erb
  106. expand_template(:erb, <<-ERB, :a => 1)
  107. <%= @instance %>
  108. <%= a %>
  109. ERB
  110.  
  111. end
  112.  
  113. def naive_erb
  114. eruby = ::Erubis::BlockAwareEruby.new(<<-ERB.dedent)
  115. <%= @instance %>
  116. <%= @a %>
  117. ERB
  118.  
  119. eruby.evaluate :a => 1, :instance => @instance
  120. end
  121. end
Add Comment
Please, Sign In to add comment