Guest User

Untitled

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