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