๐ถ Immutability is faster ๐ถ
Another +100 respect to immutability and Go
#go #memory #optimizations
# [ $davids.sh ] ยท message #216
๐ถ Immutability is faster ๐ถ
Another +100 respect to immutability and Go
#go #memory #optimizations
@ [ $davids.sh ] ยท # 1152
!Disclaimer 1! This is specifically about Golang; the situation in other languages (like Java) might be completely opposite.
!Disclaimer 2! What's said here doesn't apply to all Go data types. For example, the content of a slice (array/vector) is itself a reference, so if you don't explicitly copy them, they will be mutable.
There are 2 types of memory: stack (linked list) and heap (graph).
Allocating and freeing data on the stack are fast operations because they don't need to be searched for. However, freeing heap memory requires using a Garbage Collector (GC).
Both the speed and the load when copying and freeing stack memory can be tens of times faster than the same operations on the heap (because the GC has to perform many additional actions to determine if it's time to free a piece of heap memory).
In Go, you can pass variables by reference or by value (which creates a copy of them).
In situations where a variable fits within the stack's memory limits and doesn't leave its scope, Go tries to allocate the variable on the stack.
Most often, passing arguments/returning from a function by value (and thus copying) will signal to Go that this piece of data is better placed on the stack.
This way, copied (immutable) structures will most often end up on the stack, meaning they will be allocated and deallocated much faster.
Cool
@ Vova hardvair smartvend ๐๏ธ๐ป ยท # 1153
You just said something about a stack, but I think that's bullshit. What the hell linked list?
@ [ $davids.sh ] ยท # 1154
I'll double-check this now, but the main point is that Go allocates a stack for each goroutine, not for each thread, and it can increase it with frames of 2 / 4 / 8 kb. It doesn't have to increase the current frame; it just finds another free chunk of memory, allocates space for the frame there, and links it to the previous one. After a function is removed from the stack, it cleans up specific individual frames.
Therefore, the stack in Go can be called a linked list (like the connections between frames, which can be located non-contiguously).
@ Vova hardvair smartvend ๐๏ธ๐ป ยท # 1155
Got it. I have no more complaints)