N
N
nakem2021-10-12 00:40:27
C++ / C#
nakem, 2021-10-12 00:40:27

When is the use of Cgo justified?

Everyone around criticizes Cgo, but he is quite popular. I understand that there are cases where cgo simply needs to be used, but in what cases should cgo be used to improve performance. Do such cases even exist?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Mamonov, 2021-10-12
@nakem

The main disadvantage of using Cgo is the performance penalty.
Calls to C/C++ are rather costly in terms of resources. C knows nothing about the data in Go and to call C it is necessary to completely save all registers and switch the stack, due to this, overhead costs increase, and performance decreases accordingly.
Using Cgo makes sense when there are large libraries written in C/C++ that can be used. At the same time, writing code in pure Go is much more expensive than using these libraries with Cgo.
> in which cases cgo should be used to improve performance
As far as I understand, when calling simple functions, performance will not improve, but rather worsen.
But I do not exclude that there are cases when there are serious calculations / hard memory management (frequent allocations / releases), when due to the fact that in this case the garbage collector will not be used, you can get performance increases.
I had a similar case in Perl, but the principle is the same.
When downloading HTML pages, the size of the RAM occupied by the script constantly increased and eventually "ate" all the memory on the server.
The task of the script was to download HTML pages, extract all links to external resources from them.
I made up my mind and wrote a C function that would fetch the page, extract the links, clear the memory, and return a list of links back to Perl. Scripts stopped constantly "swelling", they could be run several times more in number on the same server + performance became clearly higher.
In general, everything depends heavily on the task, but I think more than 90% of cases will be due to the fact that it is much cheaper to use a ready-made C / C ++ library with Cgo than to rewrite this library in pure Go.

D
Dmitry Shitskov, 2021-10-12
@Zarom

When justified, in my case - the use of libraries in C.
We have equipment that comes with proprietary libraries in C to control it. Reversing them was expensive. Accordingly, cgo would allow these libraries to be used in a go service at minimal cost.

V
Vasily Bannikov, 2021-10-12
@vabka

The description of the package directly says

Cgo enables the creation of Go packages that call C code.

Not a word about performance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question