This is a creation in Article, where the information may have evolved or changed. It's a common practice to implement a memory allocator on your own in C + +, and people who have written a few years of C/s programs may have done something like this. One of the important reasons for this is that C + + does not support garbage collection. But since the go language already supports garbage collection, is it necessary to write a memory allocator on your own? Let's do a simple test to see what the results are. Test platform: Os:ubuntu 12.04 x86_64cpu:i5 2.27gmemory:8g
Ben1.go Self Implementation Memory allocator package main
Type Pool struct {
buf []byte
}
Func (P *pool) alloc (size int) []byte{
If Len (p.buf) < size{
L: = 1024x768 * 1024x768
for
l < size{
L + = l
if l <= 0 {
panic ("Out of Memory")
}
}
p.buf = Make ([]byte, L)
}buff: = p.buf[:size]p.buf = P.buf[size:]return Buff
}
Func Main () {
var p poolfor I: = 0; i < 10000000;i++ {
_ = P.alloc (+)
}
}
Ben2.go system memory Allocator package Main
Func Main () {
For
I: = 0; i < 10000000;i++ {
_ = Make ([]byte, +)
}
}
Compile test: Go build ben1.gotime./ben1go build Ben2.gotime./ben2
Test results:
| Number of |
Ben1 (s) |
Ben2 (s) |
| 1 |
0.308 |
2.057 |
| 2 |
0.304 |
2.048 |
| 3 |
0.308 |
2.093 |
| Average |
0.307 |
2.066 |
Conclusion: It can be seen that the implementation time of the memory allocator is approximately one-tenth of the system memory allocator, which is almost an order of magnitude difference. Therefore, it is necessary to use a custom memory allocator for some specific scenarios, such as network libraries. Because the Go language provides garbage collection, it is much simpler to implement a custom memory allocator compared to a C + +. However, for a custom memory allocator, you also need to be aware of synchronization issues under multiple goroutine.