结构体到磁盘的高效 Go 序列化:实现最小膨胀
尽管 gob 序列化产生了膨胀的输出,但更深入的分析表明后续相同类型的条目仅产生 12 字节的开销。此开销表示对长度为 4 字节(包括长度前缀)的两个字符串进行编码所需的最小大小。
要减小总体文件大小,请考虑以下策略:
代码演示:
以下 Go 代码演示了所讨论的各种方法:
package main import ( "bytes" "compress/bzip2" "compress/flate" "compress/gzip" "compress/zlib" "encoding/gob" "fmt" "io" ) type Entry struct { Key string Val string } func main() { // Create test data entries := make([]Entry, 1000) for i := 0; i < 1000; i++ { entries[i].Key = fmt.Sprintf("k%03d", i) entries[i].Val = fmt.Sprintf("v%03d", i) } // Test different encoding/compression techniques for _, name := range []string{"Naked", "flate", "zlib", "gzip", "bzip2"} { buf := &bytes.Buffer{} var out io.Writer switch name { case "Naked": out = buf case "flate": out, _ = flate.NewWriter(buf, flate.DefaultCompression) case "zlib": out, _ = zlib.NewWriterLevel(buf, zlib.DefaultCompression) case "gzip": out = gzip.NewWriter(buf) case "bzip2": out, _ = bzip2.NewWriter(buf, nil) } enc := gob.NewEncoder(out) for _, e := range entries { enc.Encode(e) } if c, ok := out.(io.Closer); ok { c.Close() } fmt.Printf("[%5s] Length: %5d, average: %5.2f / Entry\n", name, buf.Len(), float64(buf.Len())/1000) } }
输出:
[Naked] Length: 16053, average: 16.05 / Entry [flate] Length: 3988, average: 3.99 / Entry [ zlib] Length: 3994, average: 3.99 / Entry [ gzip] Length: 4006, average: 4.01 / Entry [bzip2] Length: 1977, average: 1.98 / Entry
从使用压缩技术的输出显着减小了文件大小,bzip2 达到了令人印象深刻的 1.98字节/条目。
以上是如何以最小的文件大小高效地将 Go 结构体序列化到磁盘?的详细内容。更多信息请关注PHP中文网其他相关文章!