How does Go compile so quickly?

Technology CommunityCategory: GolangHow does Go compile so quickly?
VietMX Staff asked 5 months ago

Go provides a model for software construction that makes dependency analysis easy and avoids much of the overhead of C-style include files and libraries.

There are three main reasons for the compiler’s speed.

  • First, all imports must be explicitly listed at the beginning of each source file, so the compiler does not have to read and process an entire file to determine its dependencies.
  • Second, the dependencies of a package form a directed acyclic graph, and because there are no cycles, packages can be compiled separately and perhaps in parallel.
  • Finally, the object file for a compiled Go package records export information not just for the package itself, but for its dependencies too. When compiling a package, the compiler must read one object file for each import but need not look beyond these files.

Go only needs to include the packages that you are importing directly (as those already imported what they need). This is in stark contrast to C/C++, where every single file starts including x headers, which include y headers etc.

Bottom line: Go’s compiling takes linear time w.r.t to the number of imported packages, where C/C++ take exponential time.