Home > Backend Development > Golang > Why Does Enabling CGO_ENABLED Slow Down Compilation, Even Without C Bindings?

Why Does Enabling CGO_ENABLED Slow Down Compilation, Even Without C Bindings?

Patricia Arquette
Release: 2024-11-26 03:29:08
Original
172 people have browsed it

Why Does Enabling CGO_ENABLED Slow Down Compilation, Even Without C Bindings?

Why CGO_ENABLED Can Slow Down Compilation, Even Without C Bindings

When creating programs that involve network usage, enabling CGO_ENABLED for compilation can result in a significant slowdown. This happens even if the program does not interact with C code. Consider the following simple HTTP server:

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi! glad you requested %s.\n", r.URL.Path[1:])
}

func main() {
    port := flag.Int("port", 9000, "")
    flag.Parse()

    http.HandleFunc("/", handler)
    err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
    if err != nil {
        log.Fatal(err)
    }
}
Copy after login

A comparison of compilation times reveals a stark difference:

% time go build
go build  0.46s user 0.06s system 131% cpu 0.396 total
% time CGO_ENABLED=0 go build
CGO_ENABLED=0 go build  3.93s user 0.15s system 143% cpu 2.849 total
Copy after login

The reason for this is that packages in the standard library are compiled without flags. When CGO_ENABLED is set, it changes the compilation flags, which means that these pre-built packages can no longer be used. Hence, a large portion of the standard library must be recompiled.

While installing packages via go build -i can alleviate this issue, it comes with its own drawbacks. Installing packages built with CGO_ENABLED=0 will enhance the speed of future builds, but it will also slow down builds that do not use it.

To resolve this conflict, consider using -installsuffix and/or -pkgdir flags, which create separate directories for different compilation modes, optimizing build efficiency and eliminating the delay associated with compiling with CGO_ENABLED.

The above is the detailed content of Why Does Enabling CGO_ENABLED Slow Down Compilation, Even Without C Bindings?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template