Home >Backend Development >Golang >Why is Compilation Time Slower with `CGO_ENABLED=0` in Go?

Why is Compilation Time Slower with `CGO_ENABLED=0` in Go?

DDD
DDDOriginal
2024-11-07 09:33:03757browse

Why is Compilation Time Slower with `CGO_ENABLED=0` in Go?

Slowdown in Compilation Time with CGO_ENABLED=0

When developing network-related Go programs, a significant discrepancy in compilation speed can be observed between builds with CGO_ENABLED=0 and those without. This is evident even in a rudimentary HTTP server example:

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)
    }
}

Compilation time benchmarks reveal a substantial slowdown:

% 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

Despite the absence of any direct C bindings, this slowdown persists. The underlying cause lies in the build process.

The Role of Build Flags

CGO_ENABLED is one of many build flags used during compilation to configure optimizations and include C code. When this flag is set to 0, pre-built standard library packages cannot be reused. Consequently, a substantial portion of the standard library must be recompiled, leading to the observed slowdown.

Alternative Approaches

While installing pre-built packages with go build -i can accelerate future builds with CGO_ENABLED=0, it does not address the issue for builds without CGO_ENABLED. To efficiently support both build configurations, separate installation directories should be utilized via the -installsuffix and -pkgdir flags. This segregation ensures that packages built with different flags do not overwrite each other.

The above is the detailed content of Why is Compilation Time Slower with `CGO_ENABLED=0` in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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