将你的TinyGo WebAssembly模块缩减60%。

With WebAssembly, small binary sizes are good. We at Fermyon like the idea of small microservices for the cloud, but even if you are building for the browser, shaving off a few kilobytes of data can speed up your app.

在WebAssembly中,小的二进制大小是好的。在Fermyon,我们喜欢为云计算提供小型微服务的想法,但即使你是为浏览器构建的,减少几千字节的数据也能加快你的应用程序。

In this post, we cover a few ways to shrink down those Go binaries when compiling to WebAssembly with TinyGo.

在这篇文章中,我们将介绍在用TinyGo编译成WebAssembly时缩小Go二进制文件的一些方法。

A Starting Point

一个出发点

Not long ago, I wrote about Writing a WebAssembly Service in TinyGo for Wagi and Spin. In that article, we created a small microservice in Go that used Spin and served out a website favicon. You can take a look at that blog post if you’d like to see the code. But for now, let’s look at how we compiled that code:

不久前,我写了一篇关于在TinyGo中为Wagi和Spin写一个WebAssembly服务的文章。在那篇文章中,我们用Go创建了一个小型的微服务,使用Spin并提供一个网站的favicon。如果你想看代码的话,可以看一下那篇博文。但现在,让我们来看看我们是如何编译这段代码的。

tinygo build -o favicon.wasm -target wasi main.go

As discussed in that post, the TinyGo compiler is able to compile most Go code to Wasm32+WASI (while Go’s standard compiler does not support the WASI extensions, and builds browser-centric code).

正如那篇文章中所讨论的,TinyGo编译器能够将大多数Go代码编译为Wasm32+WASI(而Go的标准编译器不支持WASI扩展,并构建以浏览器为中心的代码)。

The output of the above command is a Wasm file named favicon.wasm:

上述命令的输出是一个名为favicon.wasm 的Wasm文件。

ls -lah *.wasm               
-rwxr-xr-x  1 technosophos  staff   1.1M May  3 16:33 favicon.wasm

Now, 1.1M is certainly not a huge file size, but we can do some things to reduce it. We’ll start by taking a look at ways to reduce size at compile time using TinyGo. Then we will look at an extra tool (Binaryen’s wasm-opt) that optimizes WebAssembly binaries regardless of the language in which they were written.

现在,1.1M当然不是一个巨大的文件大小,但我们可以做一些事情来减少它。我们将首先看看如何在编译时使用TinyGo来减少大小。然后,我们将看看一个额外的工具(Binaryen'swasm-opt ),它可以优化WebAssembly二进制文件,而不管它们是用什么语言编写的。

One thing we will not cover here is code-level optimizations. For example, not using the fmt package can shrink down the binary si...

开通本站会员,查看完整译文。

Accueil - Wiki
Copyright © 2011-2024 iteam. Current version is 2.137.1. UTC+08:00, 2024-11-15 10:24
浙ICP备14020137号-1 $Carte des visiteurs$