結構體到磁碟的高效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中文網其他相關文章!