GolangNote

Golang笔记

golang boltdb tip

Permalink

bolt 作者提供的 boltdb 优化思路

plaintext: 优化
1
2
3
4
5
Be sure to check errors from `View()` and `Update()`. 
For example, there's a missing error check in NewList().
It's more efficient to use `binary.BigEndian.PutUint64()` instead of `fmt.Sprintf()` to represent ids. 
For one thing, it's much faster to encode & decode. 
Second of all, when you use a stringified representation then it won't insert sequentially.

官方的一个栗子:

Go: 优化例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
func (s *Store) CreateUser(u *User) error {
    return s.db.Update(func(tx *bolt.Tx) error {
        // Retrieve the users bucket.
        // This should be created when the DB is first opened.
        b := tx.Bucket([]byte("users"))

        // Generate ID for the user.
        // This returns an error only if the Tx is closed or not writeable.
        // That can't happen in an Update() call so I ignore the error check.
        id, _ := b.NextSequence()
        u.ID = int(id)

        // Marshal user data into bytes.
        buf, err := json.Marshal(u)
        if err != nil {
            return err
        }

        // Persist bytes to users bucket.
        return b.Put(itob(u.ID), buf)
    })
}

// itob returns an 8-byte big endian representation of v.
func itob(v int) []byte {
    b := make([]byte, 8)
    binary.BigEndian.PutUint64(b, uint64(v))
    return b
}

type User struct {
    ID int
    ...
}

byte to int 相互转换:

Go: byte to int 相互转换
1
2
3
4
5
6
7
8
func Btoi(b []byte) int {
	s0, _ := strconv.Atoi(string(b))
	return s0
}

func Itob(i int) []byte {
	return []byte(strconv.Itoa(i))
}

另外一个,使用字节

Go: 使用字节
1
2
3
4
5
6
7
8
9
func itob(v int64) []byte {
	b := make([]byte, 8)
	binary.BigEndian.PutUint64(b, uint64(v))
	return b
}

func btoi(v []byte) int64 {
	return int64(binary.BigEndian.Uint64(v))
}

时间戳还原:

Go: 时间戳还原
1
timestamp := time.Unix(int64(binary.BigEndian.Uint64(v)), 0)

本文网址: https://golangnote.com/topic/166.html 转摘请注明来源

Related articles

Golang Range 的性能提升Tip

Go 语言里使用 range 可以方便遍历数组(array)、切片(slice)、字典(map)和信道(chan)。这里主要关注他们的性能。...

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Golang WebAssembly 了解一下

Go 1.11 起开始支持 WebAssembly ,也就是说以后可以使用任何语言作为“前端语言”来进行 Web 开发。...

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Write a Comment to "golang boltdb tip"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms