-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunsafe_bytes_to_string_test.go
More file actions
49 lines (39 loc) · 1.19 KB
/
unsafe_bytes_to_string_test.go
File metadata and controls
49 lines (39 loc) · 1.19 KB
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
package golang_benchmarks
// go test -bench=. -benchmem ./unsafe_bytes_to_string_test.go
import (
"testing"
"unsafe"
)
func BenchmarkSafeToString(b *testing.B) {
bytes := []byte("Hello World")
for b.Loop() {
ToString(bytes)
}
}
func BenchmarkUnsafeToStringWithPtr(b *testing.B) {
bytes := []byte("Hello World")
for b.Loop() {
ToStringWithUnsafePointer(bytes)
}
}
func BenchmarkUnsafeToStringWithoutPtr(b *testing.B) {
bytes := []byte("Hello World")
for b.Loop() {
ToStringWithUnsafeString(bytes)
}
}
func ToString(bytes []byte) string {
return string(bytes)
}
func ToStringWithUnsafePointer(bytes []byte) string {
return *(*string)(unsafe.Pointer(&bytes))
}
func ToStringWithUnsafeString(bytes []byte) string {
if len(bytes) == 0 {
return ""
}
return unsafe.String(unsafe.SliceData(bytes), len(bytes))
}
// BenchmarkSafeToString-10 98654934 12.25 ns/op 16 B/op 1 allocs/op
// BenchmarkUnsafeToStringWithPtr-10 585261528 2.056 ns/op 0 B/op 0 allocs/op
// BenchmarkUnsafeToStringWithoutPtr-10 592686736 2.029 ns/op 0 B/op 0 allocs/op