Table of Contents
//go:embed adds file contents to the binary
? Binary size impact: It's about the data, not the directive
? How to check the impact
? Tips to minimize impact
⚖️ Trade-offs: Convenience vs. Size
Bottom line
Home Backend Development Golang How does go embed affect my binary size?

How does go embed affect my binary size?

Jul 30, 2025 am 04:28 AM

//go:embed will not increase the binary volume itself, but the embedded files will directly increase the volume. 1. Using //go:embed will compile the file contents (such as HTML, JSON, images, etc.) into a binary file, resulting in an increase in volume that is comparable to the size of the embedded file. 2. The instruction itself has no additional overhead, and the volume growth depends entirely on the amount of data embedded. For example, embedding 5 MB of JavaScript files will increase the binary file by about 5 MB. 3. The impact can be evaluated by comparing the binary sizes before and after the build (such as using go build and ls -lh) or using go tool nm to check the data segment. 4. To reduce the impact, embedding large files (such as videos, uncompressed resources) should be avoided, compression is preferred (such as minimizing HTML/CSS/JS), and consider embedding in production environments and loading externally in development using build tags. 5. The trade-off is: //go:embed improves deployment convenience and eliminates runtime I/O errors, but at the cost of getting bigger binary, starting slower, and possibly containing unused resources. In short, //go:embed itself does not cause expansion, and volume growth is entirely determined by the embedding file. Embedding for small or medium resources (such as configuration, templates, static interfaces) is a reasonable choice, while for large resources, it needs to be carefully evaluated or pre-optimized.

How does go embedded affect my binary size?

Using Go's //go:embed directly doesn't inherently bloat your binary size more than other ways of including data — but it does embed files directly into the binary, so the impact depends on what you're embedding and how you're using it.

How does go embedded affect my binary size?

Here's what you need to know:


//go:embed adds file contents to the binary

When you use //go:embed , the content of the specified files (like HTML, JSON, images, etc.) is compiled directly into the executable. This means:

How does go embedded affect my binary size?
  • The binary size increases by roughly the size of the embedded files.
  • No external files are needed at runtime — everything is self-contained.

For example:

 //go:embed templates/*
var templatesFS embedded.FS

All files in the templates/ directory are now part of the binary.

How does go embedded affect my binary size?

? Binary size impact: It's about the data, not the directive

The //go:embed directive itself adds no overhead. The size increases come entirely from the files you embed .

Embedded Content Size Impact
10 KB of JSON ~ 10 KB
1 MB image ~ 1 MB
Static site (HTML/CSS) Can add several MB

So if you embed a 5 MB JavaScript bundle, your binary will be ~5 MB larger — whether you use embed.FS , go:generate , or a third-party tool.


? How to check the impact

You can compare binary sizes before and after embedding:

 # Build without embedded assets
go build -o app-no-assets .

# Build with embedded assets
go build -o app-with-assets .

# Compare sizes
ls -lh app-*

Also, use go tool nm or objdump to see if large strings or data sections were added.


? Tips to minimize impact

If binary size matters (eg, for microservices, CLI tools, or cold starts in serverless):

  • Avoid embedding large files like videos, big images, or unminified JS/CSS.
  • Compress assets if possible (eg, minify HTML/CSS/JS before embedding).
  • Use build tags to create "lite" versions without embedded assets in development:
     //go:embed production-assets/*
    // build release
  • Consider loading assets externally in dev , but embedded only in production builds.

  • ⚖️ Trade-offs: Convenience vs. Size

    //go:embed makes deployment easier — one binary, no dependencies. But you pay with size.

    It's a classic trade-off:

    • ✅ Simpler deployment
    • ✅ No I/O errors loading templates/assets
    • ❌ Larger binary
    • ❌ Slower startup if loading huge embedded FS
    • ❌ Binary may contain unused assets

    Bottom line

    //go:embed doesn't add bloat by itself — it just includes your files.
    The bigger the files you embed, the bigger your binary.

    So: embed wisely. For small to modern assets (configs, templates, static UI), it's perfectly fine. For large media or bundles, think twice — or optimize them first.

    Basically: you get exactly what you ask for — no magic, no hidden tax, just your files in the binary.

    The above is the detailed content of How does go embed affect my binary size?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1594
276
go by example http middleware logging example go by example http middleware logging example Aug 03, 2025 am 11:35 AM

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

reading from stdin in go by example reading from stdin in go by example Jul 27, 2025 am 04:15 AM

Use fmt.Scanf to read formatted input, suitable for simple structured data, but the string is cut off when encountering spaces; 2. It is recommended to use bufio.Scanner to read line by line, supports multi-line input, EOF detection and pipeline input, and can handle scanning errors; 3. Use io.ReadAll(os.Stdin) to read all inputs at once, suitable for processing large block data or file streams; 4. Real-time key response requires third-party libraries such as golang.org/x/term, and bufio is sufficient for conventional scenarios; practical suggestions: use fmt.Scan for interactive simple input, use bufio.Scanner for line input or pipeline, use io.ReadAll for large block data, and always handle

How does the switch statement work in Go? How does the switch statement work in Go? Jul 30, 2025 am 05:11 AM

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.

go by example generics go by example generics Jul 29, 2025 am 04:10 AM

Go generics are supported since 1.18 and are used to write generic code for type-safe. 1. The generic function PrintSlice[Tany](s[]T) can print slices of any type, such as []int or []string. 2. Through type constraint Number limits T to numeric types such as int and float, Sum[TNumber](slice[]T)T safe summation is realized. 3. The generic structure typeBox[Tany]struct{ValueT} can encapsulate any type value and be used with the NewBox[Tany](vT)*Box[T] constructor. 4. Add Set(vT) and Get()T methods to Box[T] without

go by example running a subprocess go by example running a subprocess Aug 06, 2025 am 09:05 AM

Run the child process using the os/exec package, create the command through exec.Command but not execute it immediately; 2. Run the command with .Output() and catch stdout. If the exit code is non-zero, return exec.ExitError; 3. Use .Start() to start the process without blocking, combine with .StdoutPipe() to stream output in real time; 4. Enter data into the process through .StdinPipe(), and after writing, you need to close the pipeline and call .Wait() to wait for the end; 5. Exec.ExitError must be processed to get the exit code and stderr of the failed command to avoid zombie processes.

What is the standard project layout for a Go application? What is the standard project layout for a Go application? Aug 02, 2025 pm 02:31 PM

The answer is: Go applications do not have a mandatory project layout, but the community generally adopts a standard structure to improve maintainability and scalability. 1.cmd/ stores the program entrance, each subdirectory corresponds to an executable file, such as cmd/myapp/main.go; 2.internal/ stores private code, cannot be imported by external modules, and is used to encapsulate business logic and services; 3.pkg/ stores publicly reusable libraries for importing other projects; 4.api/ optionally stores OpenAPI, Protobuf and other API definition files; 5.config/, scripts/, and web/ store configuration files, scripts and web resources respectively; 6. The root directory contains go.mod and go.sum

how to break from a nested loop in go how to break from a nested loop in go Jul 29, 2025 am 01:58 AM

In Go, to break out of nested loops, you should use labeled break statements or return through functions; 1. Use labeled break: Place the tag before the outer loop, such as OuterLoop:for{...}, use breakOuterLoop in the inner loop to directly exit the outer loop; 2. Put the nested loop into the function, and return in advance when the conditions are met, thereby terminating all loops; 3. Avoid using flag variables or goto, the former is lengthy and easy to make mistakes, and the latter is not recommended; the correct way is that the tag must be before the loop rather than after it, which is the idiomatic way to break out of multi-layer loops in Go.

How do you work with environment variables in Golang? How do you work with environment variables in Golang? Aug 19, 2025 pm 02:06 PM

Goprovidesbuilt-insupportforhandlingenvironmentvariablesviatheospackage,enablingdeveloperstoread,set,andmanageenvironmentdatasecurelyandefficiently.Toreadavariable,useos.Getenv("KEY"),whichreturnsanemptystringifthekeyisnotset,orcombineos.Lo

See all articles