exbytes

package
v0.0.0-...-261b507 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 27, 2019 License: GPL-3.0 Imports: 2 Imported by: 0

Documentation

Overview

Package exbytes 收集常规的 []byte 操作,作为 go 标准库 bytes 的扩展。 避免重复编写 []byte 相关操作代码,集中在一起更有利于优化代码,保证代码质量。

这个包会使用一些特殊的操作来减少内存开销,已获得更好的程序性能。

我也会在这个包重写 标准库 bytes 里面的一些方法,以适用于不同场景的性能优化。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Replace

func Replace(s, old, new []byte, n int) []byte

Replace 思路来源于 bytes.Replace,bytes.Replace 总是返回 s 的副本, 有些场景源数据生命周期非常短,且可以原地替换,如果这么实现可以减少极大的内存分配。

len(old) >= len(new) 会执行原地替换,这回浪费一部分空间,但是会减少内存分配, 建议输入生命周期较短的数据, len(old) < len(new) 会调用 bytes.Replace 并返回一个替换后的副本。

最佳实践是使用 Replace 的结果覆盖源变量,避免再次对源数据引用,导致访问过时的数据,并且数据内容错乱,如下:

var s []byte
s = exbytes.Replace(s, []byte(" "), []byte(""), -1)

关于字符串可以结合 exstrings.UnsafeToBytes 来实现,要避免常量字符串和字面量字符串,否者会产生运行时错误。

func ToString

func ToString(s []byte) string

ToString 把 []byte 转换为 string 没有多余的内存开销。

使用该方法需要了解到 []byte 将和 string 公用一块内存, 修改 []byte 的数据将导致 string 发生变化, 这打破了字符串不可以修改的特性,如果你恰恰需要这么做,可能非常的有用。 要保证字符串不可变的特性,就必须保证 []byte 不会发生变化,或者立即消费 string, 往往这个非常的有用, 比如我们需要打印日志:

b := []byte("hello word") log.Println(ToString(b))

尽快的消耗掉 string 是个好主意, 也可以遗忘掉 []byte 后面不在使用这个, 而只使用 string。

比较好的例子是 exstrings.UnsafePad 系列函数,在函数内部使用 []byte 作为字符串缓冲区,返回字符串通过该方法转换。

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL