-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
benchmark.cr
57 lines (48 loc) · 1.22 KB
/
benchmark.cr
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
require "benchmark"
module ReverseString
def self.reverse(input : String) : String
input.reverse
end
end
module ReverseStringArray
def self.reverse(input : String) : String
result = Array(Char).new(input.size)
input.each_char do |char|
result.unshift(char)
end
result.join
end
end
module ReverseStringStringBuild
def self.reverse(input : String) : String
result = String.build(input.size) do |builder|
(0...input.size).reverse_each do |i|
builder << input[i]
end
end
end
end
puts "ReverseString, short string"
puts Benchmark.measure {
ReverseString.reverse("Hello World")
}
puts "ReverseStringArray, short string"
puts Benchmark.measure {
ReverseStringArray.reverse("Hello World")
}
puts "ReverseStringStringBuild, short string"
puts Benchmark.measure {
ReverseStringStringBuild.reverse("Hello World")
}
puts "ReverseString, long string"
puts Benchmark.measure {
ReverseString.reverse("Hello World" * 1000)
}
puts "ReverseStringArray, long string"
puts Benchmark.measure {
ReverseStringArray.reverse("Hello World" * 1000)
}
puts "ReverseStringStringBuild, long string"
puts Benchmark.measure {
ReverseStringStringBuild.reverse("Hello World" * 1000)
}