forked from fastruby/fast-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sub!-vs-gsub!-vs-[]=.rb
44 lines (35 loc) · 931 Bytes
/
sub!-vs-gsub!-vs-[]=.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
require "benchmark/ips"
URL = "http://www.thelongestlistofthelongeststuffatthelongestdomainnameatlonglast.com/wearejustdoingthistobestupidnowsincethiscangoonforeverandeverandeverbutitstilllookskindaneatinthebrowsereventhoughitsabigwasteoftimeandenergyandhasnorealpointbutwehadtodoitanyways.html"
def fast
s = URL.dup
s["http://"] = ""
end
def slow_1
s = URL.dup
s.sub! "http://", ""
end
def slow_2
s = URL.dup
s.gsub! "http://", ""
end
def slow_3
s = URL.dup
s[%r{http://}] = ""
end
def slow_4
s = URL.dup
s.sub! %r{http://}, ""
end
def slow_5
s = URL.dup
s.gsub! %r{http://}, ""
end
Benchmark.ips do |x|
x.report("String#['string']=") { fast }
x.report("String#sub!'string'") { slow_1 }
x.report("String#gsub!'string'") { slow_2 }
x.report("String#[/regexp/]=") { slow_3 }
x.report("String#sub!/regexp/") { slow_4 }
x.report("String#gsub!/regexp/") { slow_5 }
x.compare!
end