原文链接: go wasm gzip 压缩
上一篇: go gzip 压缩与解压
下一篇: go 解压缩文件夹
第一次执行效果go比js快, 但是多次执行的话会比js慢...
还是同样的文件, 这次就是js快了...
go文件
package main
import (
"bytes"
"compress/gzip"
"syscall/js"
)
//go:export ZipGo
func ZipGo(this js.Value, args []js.Value) interface{} {
f := args[0]
buf := make([]byte, f.Length())
js.CopyBytesToGo(buf, f)
var res bytes.Buffer
gz := gzip.NewWriter(&res)
gz.Write(buf)
gz.Flush()
outLen := len(res.Bytes())
zipped := js.Global().Get("Uint8Array").New(outLen)
js.CopyBytesToJS(zipped, res.Bytes())
return js.ValueOf(zipped)
}
func registerCallbacks() {
js.Global().Set("ZipGo", js.FuncOf(ZipGo))
}
func main() {
c := make(chan struct{}, 0)
println("WASM Go Initialized")
registerCallbacks()
<-c
}
// set GOARCH=wasm
// set GOOS=js
// go build -o lib.wasm file-go.go
// tinygo build -o fib-list.wasm -target=wasm fib-list.go
html
对比pako库
https://raw.githubusercontent.com/nodeca/pako/master/dist/pako.min.js
http://nodeca.github.io/pako/#gzip
<!DOCTYPE html>
<!--
Copyright 2018 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>
<head>
<meta charset="utf-8"/>
<title>Go wasm</title>
</head>
<body>
<script src="../wasm_exec.js"></script>
<script src="./pako.min.js"></script>
<script>
if (!WebAssembly.instantiateStreaming) {
// polyfill
WebAssembly.instantiateStreaming = async (resp, importObject) => {
const source = await (await resp).arrayBuffer();
return await WebAssembly.instantiate(source, importObject);
};
}
const go = new Go();
let mod, inst;
WebAssembly.instantiateStreaming(fetch("./lib.wasm"), go.importObject).then(
async result => {
mod = result.module;
inst = result.instance;
await go.run(inst);
}
);
function zipGo(buf) {
let st = +new Date()
let res = ZipGo(buf)
let ed = +new Date()
console.log('zipgo res', res)
console.log('zipgo len', res.length)
console.log('zipgo time', ed - st)
}
function zipJs(buf) {
let st = +new Date()
let res = pako.gzip(buf)
let ed = +new Date()
console.log('zipjs res', res)
console.log('zipjs len', res.length)
console.log('zipjs time', ed - st)
}
function fileChange(event) {
let fileList = event.target.files
// let f = fileList[0]
// let buf = new Uint8Array(f)
// console.log(buf)
let reader = new FileReader();
reader.onload = function (data) {
let buf = new Uint8Array(this.result)
zipGo(buf)
zipJs(buf)
}
reader.readAsArrayBuffer(fileList[0])
}
</script>
<input type="file"
id="file"
onchange="fileChange(event)"
multiple>
<button onclick="run()">run</button>
</body>
</html>