-
Notifications
You must be signed in to change notification settings - Fork 0
/
performance.rb
59 lines (43 loc) · 1.19 KB
/
performance.rb
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
# frozen_string_literal: true
$LOAD_PATH.unshift File.expand_path('../lib', __dir__)
require 'benchmark/ips'
require 'berns'
require 'cgi/escape'
EMPTY = ''
SPACE = ' '
def to_attributes(attributes)
return EMPTY if attributes.empty?
string = +''
attributes.each do |attr, value|
string << SPACE
to_attribute(attr, value, string)
end
string.strip!
string
end
def to_attribute(attribute, value, string = +'')
if value.is_a?(FalseClass) # rubocop:disable Style/CaseLikeIf
# noop
elsif value.is_a?(TrueClass)
string << attribute.to_s
elsif value.is_a?(Hash)
value.each do |attr, subval|
string << SPACE
to_attribute(attr.nil? ? attribute : "#{ attribute }-#{ attr }", subval, string)
end
string.strip!
else
string << %(#{ attribute }="#{ CGI.escapeHTML(value.to_s) }")
end
string
end
def element(tag, attributes = nil)
content = yield if block_given?
"<#{ tag } #{ to_attributes(attributes) }>#{ content }</#{ tag }>"
end
ATTRS = { class: 'class', data: { attr: 'value' } }.freeze
Benchmark.ips do |x|
x.report('ruby') { element('p', ATTRS) { 'Content' } }
x.report('c-ext') { Berns.element('p', ATTRS) { 'Content' } }
x.compare!
end