Why is cgo so slow?
Your testing code compares the execution time of C and Go functions run 100 million times each. The C function takes longer than the Golang function, and you are concerned that something is wrong with your testing code.
The high overhead of calling C/C code via CGo makes CGo calls best minimized. In the provided example, it might be more efficient to create a C loop instead of calling a CGo function repeatedly in a loop.
The Go runtime's setup for its threads can break the expectations of C code in several ways:
Therefore, CGo takes the safe approach of running C code in a separate thread with a traditional stack.
Unlike languages like Python where rewriting code hotspots in C was common for speeding up programs, Go's performance gap between C and Go code is much smaller. Consider reserving CGo for interfacing with existing libraries, possibly with small C wrapper functions to reduce the number of calls required from Go.
The above is the detailed content of Why is my Cgo code slower than expected Go code?. For more information, please follow other related articles on the PHP Chinese website!