Closure (closure) is also a very common coding pattern, because it implicitly carries context variables, so that the algorithm code can be more concise.
But behind any "convenience" and "elegance" is often a more complex implementation mechanism, which is nothing more than a syntax sugar or compiler that hides the details. Ultimately, these will become additional costs at run time by CPU, runtime burden. Even for unreasonable use, causing performance problems.
Use a few code snippets to see the possible hassles.
The performance difference for a single call is a bit large (different environment results will be different), but will this be related to the anonymous function itself?
It seems to be so. But the next problem is even more troublesome. (The code is only for presentation and does not guarantee logical consistency)
First, the closure refers to the original environment variable, causing Y to escape to the heap, which inevitably increases the number of GC scans and objects retrieved.
Next, the same is true because the closure refers to the original object, which results in data contention (race).
As can be seen, closures may not always "simplify" things. As you learn about the Go bottom-up implementation, you'll see that all "simple" is piled up by the compiler or run-time with a bunch of complicated processes.
Latest news, please scan the code attention
Go Performance Optimization Tips 5/10