Go Memory Optimizer (i)-struct

Source: Internet
Author: User

Principle

About Golang The writing order of field in the same struct will be different for different memory allocation sizes. The main reasons are as follows: The field memory allocation within a struct is based on 4 B and must be exclusive at 4B.

Example

type A1 struct {    a bool    b uint32    c bool    d uint32    e uint8    f uint32    g uint8}

Calculate the amount of memory that A1 needs to occupy:

  1. First, the 1th 4B in the a,a is a bool type, occupies 1B, the remaining 3B
  2. Then look at B is UInt32, Occupy 4B, the remaining 3B, so offset to the next 4B space, then we will find 3B did not put things, was wasted
  3. Down, A1 to occupy 28B of space
    According to 1, 22 steps are easy to see, there is a lot of wasted space.

Optimization:

type A2 struct {    a bool    c bool    e uint8    g uint8    b uint32    d uint32    f uint32}
  1. First, the 1th 4B in the a,a is a bool type, occupies 1B, the remaining 3B
  2. C is bool, take 1B, put the remaining 2B after
  3. D is uint8, Occupy 1B, put the remaining 1B after
  4. Turn down
    This can make memory usage much higher.

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.