Go Performance Optimization Tips 3/10

Source: Internet
Author: User

The built-in map type is required. First, the type is used very often, and second, the runtime enables deep-level optimizations (such as String conversions, GC scans, and so on). However, it does not mean that everything is good, there are still a lot of places needing special attention.

1. Preset capacity

Map expands on demand, but requires a copy of the data and a cost of re-hashing. Where possible, adequate capacity should be preset as far as possible to prevent such behavior from occurring.


From the results, the default capacity map obviously performs better and significantly reduces heap memory allocation times.

2. Direct Storage

For small objects, it is far more efficient to direct data to a map than to use pointers. This not only reduces heap memory allocations, but the key is that the garbage collector does not scan non-pointer-type Key/value objects.

Write a sample comparison and note that the function call is adjusted for 33 rows.

Pointer mode:

Value mode:

The "huge" difference can be seen from the percentage of time that the GC occupies in the two output.

Hint: Map has a limit on key and value data storage length.

3. Space shrinkage

Unfortunately, map does not shrink the "no longer used" space. Even if you delete all the key values, it still retains memory space for later use.

Even if all the data is emptied, the space is still not released. The workaround is to cancel the 23-line comment, or replace it with a new map object.

Tip: If you use a Map object for a long time (for example, as a cache container), it might be better to occasionally replace it with "new". Also, int key is faster than string key.

Latest news, please scan the code attention

Go Performance Optimization Tips 3/10

Related Article

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.