bson和json性能對比

測試1000個數據 每一個數據10個字節,分別使用字節、json、bson方式 存儲,並用gzip壓縮 json


Bson測試

package main

import (
    "bytes"
    "compress/gzip"
    "fmt"
    "labix.org/v2/mgo/bson"
    "math/rand"
)

type HisCollection struct {
    RTValues []RTValue
}

type RTValue struct {
    Time   int32
    Status int16
    Value  float32
}

func main() {
    fmt.Println("start")

    size := 1000
    col := make([]RTValue, size)

    for i := 0; i < size; i++ {
        col[i] = RTValue{Time: int32(i), Status: 100, Value: rand.Float32()}
    }

    his := HisCollection{RTValues: col}
    data, err := bson.Marshal(&his)
    if err != nil {
        panic(err)
    }
    //    fmt.Println(data)
    fmt.Println("bson byte:", len(data))

    var compress_data_buf bytes.Buffer
    writer := gzip.NewWriter(&compress_data_buf)
    defer writer.Close()

    writer.Write(data)
    writer.Flush()

    fmt.Println("bson gzip compress:",len(compress_data_buf.Bytes()))

}


Rawcode

package main

import (
    "bytes"
    "compress/gzip"
    "fmt"
    "math/rand"
    "openplant/opnet"
)

func main() {
    var compress_data_buf bytes.Buffer
    writer := gzip.NewWriter(&compress_data_buf)
    defer writer.Close()

    size := 1000
    for i := 0; i < size; i++ {
        writer.Write(opnet.WarpInt32ToByte(int32(i)))
        writer.Write(opnet.WarpInt16ToByte(int16(100)))
        writer.Write(opnet.WarpFloat32ToByte(rand.Float32()))
    }
    writer.Flush()
    fmt.Println("raw data:", 10000)
    fmt.Println("raw data gzip compress:", len(compress_data_buf.Bytes()))
}


Jsonip

package main

import (
    "bytes"
    "compress/gzip"
    "encoding/json"
    "fmt"
    "math/rand"
)

type HisCollection struct {
    RTValues []RTValue
}

type RTValue struct {
    Time   int32
    Status int16
    Value  float32
}

func main() {
    fmt.Println("start")

    size := 1000
    col := make([]RTValue, size)

    for i := 0; i < size; i++ {
        col[i] = RTValue{Time: int32(i), Status: 100, Value: rand.Float32()}
    }

    his := HisCollection{RTValues: col}

    data, err := json.Marshal(&his)

    fmt.Println("json string:", string(data))
    fmt.Println("json string:", len(string(data)))

    if err != nil {
        panic(err)
    }
    //    fmt.Println(data)
    fmt.Println("json byte:", len(data))

    var compress_data_buf bytes.Buffer
    writer := gzip.NewWriter(&compress_data_buf)
    defer writer.Close()

    writer.Write(data)
    writer.Flush()

    fmt.Println("json gzip compress:", len(compress_data_buf.Bytes()))

}
輸出結果:
raw data: 10000
raw data gzip compress: 6553

json string: 44524
json byte: 44524
json gzip compress: 8125

bson byte: 46910
bson gzip compress: 9721


結果bson比json還大一點
我的結論是BSON對比json更加適合存儲,在傳輸上沒有太大優點
string

  BSON相對JSonit

1.更快的遍歷速度io

2.操做更簡易class

3.增長了額外的數據類型import

相關文章
相關標籤/搜索