Hi all, Closures have some cost and we are advised to not use them in code that strives to be performant. However the quick benchmark I did showed this is not so currently but I suppose the benchmark is way too trivial.
What optimisation will the official golang compiler try to do and what is the long term plan for this? AFAIK there are two types of costs for closures: 1. Some data may need to be allocated in heap and will be GC collected rather than stack allocated and autorelease. 2. Typically inner functions are assigned to a variable. So at the moment the body is called via the variable, the runtime needs to check what the variable points to. Note that both of these can be optimized away depending on things such as the definition, call and size of function body, number of free variables. In the absolute trivial benchmark I created - it seems all calls are practically the same (difference slowest to fastest is 2%). However I am not sure how well this corresponds to typical behavior. - When will a closure call be inlined? - How long can the body be or how many free variables can be for the compiler to optimize this? - What can break the optimization? Kind regards: al_shopov Benchmark here: https://go.dev/play/p/2Z7cg0tJVAe Results: BenchmarkNoclosurecall-12 92 12593210 ns/op BenchmarkClosurecall-12 91 12327950 ns/op BenchmarkClosurecallimmediate-12 92 12359107 ns/op -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/golang-nuts/CAP6f5M%3DOhY0mQ%3DWXXaHge4WWttTgBqcXLdbVuJRVstNHjCKxxQ%40mail.gmail.com.
