[Go language] memory allocator performance test

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.