“This is the 23rd day of my participation in the First Challenge 2022. For details: First Challenge 2022.”
preface
Arrays are a common data structure used in programming. In GO, there are both slices whose length can be changed and arrays whose length cannot be changed after initialization. This article discusses the characteristics of arrays
Several features of arrays
An array is a contiguous storage area. The benefits of memory continuity are:
- The CPU can cache data longer.
- Easy to compute indexes and quick to iterate over elements.
Unlike other languages, arrays in GO cannot be expanded. Whether it’s passed as a parameter when calling a function or a copy of the type b=a, it’s value copy. This means that large arrays need to be avoided as much as possible to avoid being copied and used as function arguments, thus consuming memory.
Array initialization
Go language arrays do
[...].int{2.3.4}
Copy the code
Initialization is done as follows, but memory allocation needs to know the exact length of the array. Length determination, including index overbounds (constants only), is done at compile time.
When I wanted to check the source code and found GO1.17, I did not find the relevant code, but only found the information of the old version on the Internet. We look at the source code below
This function calls typecheckarraylit to count the number of elements in the array by iterating over them.
Compile time optimization
As we all know, arrays, as a contiguous storage space, are bound to have a need for contiguous blank memory. If the array length is large, it is not appropriate to keep the array on the stack, so when the array length is larger than 4, the array is put into the static read-only area of memory. However, when the size of the array is not large, putting it in a static read-only area will cause too much performance, so the array will be put on the stack.