Golang高性能编程实践

腾讯技术工程 发表于 7月以前  | 总阅读数:290 次

go 中高性能编程是一个经久不衰的话题,本文尝试从实践及源码层面对 go 的高性能编程进行解析。

1. 为什么要进行性能优化

服务上线前,为什么要进行压测和性能的优化?

一个例子,content-service 在压测的时候发现过一个问题: 旧逻辑为了简化编码,在进行协议转换前,会对某些字段做一个 DeepCopy,因为转换过程需要原始数据,但我们完全可以通过一些处理逻辑的调整,比如调整先后顺序等移除 DeepCopy。优化前后性能对比如下:

阶段 AVG(ms) P95(ms) P99(ms) CPU/MEM
优化前 67.96 153.59 212.85 100%/34%
优化后 9.12 23.22 38.98 84%/34%

性能有 7 倍左右提升,改动很小,但折算到成本上的收益是巨大的。

在性能优化上任何微小的投入,都可能会带来巨大的收益

那么,如何对 go 程序的性能进行度量和分析?

2. 度量和分析工具

2.1 Benchmark

2.1.1 Benchmark 示例
func BenchmarkConvertReflect(b *testing.B) {
    var v interface{} = int32(64)
    for i:=0;i<b.N;i++{
        f := reflect.ValueOf(v).Int()
        if f != int64(64){
            b.Error("errror")
        }
    }
}

函数固定以 Benchmark 开头,其位于_test.go 文件中,入参为 testing.B 业务逻辑应放在 for 循环中,因为 b.N 会依次取值 1, 2, 3, 5, 10, 20, 30, 50,100.........,直至执行时间超过 1s

可通过go test --bench命令执行 benchmark,其结果如下:

➜  gotest666 go test --bench='BenchmarkConvertReflect' -run=none
goos: darwin
goarch: amd64
pkg: gotest666
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkConvertReflect-12      520200014            2.291 ns/op

--bench='BenchmarkConvertReflect', 要执行的 benchmark。需注意:该参数支持模糊匹配,如--bench='Get|Set' ,支持./...-run=none,只进行 Benchmark,不执行单测

BenchmarkConvertReflect, 在 1s 内执行了 520200014 次,每次约 2.291ns

2.1.2 高级用法
➜  gotest666 go test --bench='Convert' -run=none -benchtime=2s -count=3 -benchmem -cpu='2,4' -cpuprofile=cpu.profile -memprofile=mem.profile -trace=xxx -gcflags=all=-l
goos: darwin
goarch: amd64
pkg: gotest666
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkConvertReflect-2       1000000000           2.286 ns/op           0 B/op          0 allocs/op
BenchmarkConvertReflect-2       1000000000           2.302 ns/op           0 B/op          0 allocs/op
BenchmarkConvertReflect-2       1000000000           2.239 ns/op           0 B/op          0 allocs/op
BenchmarkConvertReflect-4       1000000000           2.244 ns/op           0 B/op          0 allocs/op
BenchmarkConvertReflect-4       1000000000           2.236 ns/op           0 B/op          0 allocs/op
BenchmarkConvertReflect-4       1000000000           2.247 ns/op           0 B/op          0 allocs/op
PASS

-benchtime=2s', 依次递增 b.N 直至运行时间超过 2s-count=3,执行 3 轮-benchmem,b.ReportAllocs,展示堆分配信息,0 B/op, 0 allos/op 分别代表每次分配了多少空间,每个 op 有多少次空间分配-cpu='2,4',依次在 2 核、4 核下进行测试-cpuprofile=xxxx -memprofile=xxx -trace=trace.out,benmark 时生成 profile、trace 文件-gcflags=all=-l,停止编译器的内联优化b.ResetTimer, b.StartTimer/b.StopItmer,重置定时器b.SetParallelism、b.RunParallel, 并发执行,设置并发的协程数

目前对 go 性能进行分析的主要工具包含:profile、trace,以下是对二者的介绍

2.2 profile

目前 go 中 profile 包括: cpu、heap、mutex、goroutine。要在 go 中启用 profile 主要有以下几种方式:

  1. 运行时函数,如 pprof.StartCPUProfile、pprof.WriteHeapProfile 等
  2. 导入 net/http/pprof 包
  3. go test 中使用-cpuprofile、-memprofile

go 中提供了 pprof 工具对 profile 进行解析,以 cpuprofile 为例,如下:

go tool pprofile cpu.profile
(pprof) top 15
Showing nodes accounting for 14680ms, 99.46% of 14760ms total
Dropped 30 nodes (cum <= 73.80ms)
      flat  flat%   sum%        cum   cum%
    2900ms 19.65% 19.65%     4590ms 31.10%  reflect.unpackEface (inline)
    2540ms 17.21% 36.86%    13280ms 89.97%  gotest666.BenchmarkConvertReflect
    1680ms 11.38% 48.24%     1680ms 11.38%  reflect.(*rtype).Kind (inline)

(pprof) list gotest666.BenchmarkConvertReflect
Total: 14.76s
ROUTINE ======================== gotest666.BenchmarkConvertReflect in /Users/zhangyuxin/go/src/gotest666/a_test.go
     2.54s     13.28s (flat, cum) 89.97% of Total
         .          .      8:func BenchmarkConvertReflect(b *testing.B) {
         .          .      9:   var v interface{} = int32(64)
     1.30s      1.41s     10:   for i:=0;i<b.N;i++{
         .     10.63s     11:       f := reflect.ValueOf(v).Int()
     1.24s      1.24s     12:       if f != int64(64){
         .          .     13:           b.Error("errror")
         .          .     14:       }
         .          .     15:   }
         .          .     16:}
         .          .     17:
(pprof)

flat,cum 分别代表了当前函数、当前函数调用函数的统计信息top、list、tree是用的最多的命令

go 也提供了 web 界面用以对各种调用进行图像化展示,可以通过-http 打开内置的 http 服务,该服务可以展示包含调用图、火焰图等信息

go tool pprof -http=":8081" cpu.profile

对于调用图,边框、字体的颜色越深,代表消耗资源越多。实线代表直接调用,虚线代表非直接调用(中间还有其他调用) 火焰图代表了调用层级,函数调用栈越长,火焰越高。同一层级,框越长、颜色越深占用资源越多 profile 是通过采样实现,存在精度问题、且会对性能有影响(比如 go routine 的 profile 采样会导致 STW)

此外,目前 123 中已经有 profile 相关的插件,具体可搜索:查看火焰图、GoMemProfile

2.3 trace

profile 可以通过采样,确定系统运行中的热点,但其基于采样的处理也有精度等问题。 因此,go 提供了 trace 工具,其基于事件的统计为解决问题提供了更详细的数据,此外 go trace 还把 P、G、Heap 等相关信息聚合在一起按照时间进行展示,如下图:

go 中启用 trace,可以通过以下方式:

  1. 通过 runtime/trace 包中相应函数,主要是 trace.Start、trace.Stop
  2. 通过导入 net/http/pprof
  3. 通过 go test 中 trace 参数

以 runtime/trace 为例,如下:

import (
    "os"
    "runtime/trace"
)

func main() {
    f, _ := os.Create("trace.out")
    trace.Start(f)
    defer trace.Stop()

    ch := make(chan string)
    go func() {
        ch <- "EDDYCJY"
    }()

    <-ch
}

go tool trace trace.out,会打开页面,结果包含如下信息:

View trace // 按照时间查看thread、goroutine分析、heap等相关信息
Goroutine analysis // goroutine相关分析
Syscall blocking profile // syscall 相关
Scheduler latency profile // 调度相关
........

实际中经常先通过 Goroutine analysis、Scheduler latency profile 等查找可能的问题点,再通过 View trace 进行全面分析。

3. 常用类型和结构

3.1 interface、reflect

通常 go 中较多的 interface、reflect 会对性能有一定影响,interface、reflect 为什么会对性能有影响?

3.1.1 interface 和 eface

go 中 interface 包含 2 种,eface、iface。eface 用于标识不含方法的 interface,iface 用于标识带方法的 interface,其相关机制不在本文介绍范围。

eface 的定义位于runtime2.gotype.go,其定义如下:

type eface struct {
    _type *_type                 // 类型信息
    data  unsafe.Pointer // 数据
}

type _type struct {
    size       uintptr  // 大小信息
    .......
    hash       uint32     // 类型信息
    tflag      tflag
    align      uint8        // 对齐信息
    .......
}

因为同时包含类型、数据,go 中所有类型都可以转换为 interface。go 中为 interface 赋值的过程,即为 eface 变量生成的过程,通过汇编可以发现,其主要通过 convT*完成位于iface.go,具体分发逻辑位于convert.go。 以指针类型为例,其转换逻辑如下:

// dataWordFuncName returns the name of the function used to convert a value of type "from"
// to the data word of an interface.
func dataWordFuncName(from *types.Type) (fnname string, argType *types.Type, needsaddr bool) {
    .............
    switch {
    case from.Size() == 2 &amp;&amp; uint8(from.Alignment()) == 2:
        return "convT16", types.Types[types.TUINT16], false
    case from.Size() == 4 &amp;&amp; uint8(from.Alignment()) == 4 &amp;&amp; !from.HasPointers():
        return "convT32", types.Types[types.TUINT32], false
    case from.Size() == 8 &amp;&amp; uint8(from.Alignment()) == uint8(types.Types[types.TUINT64].Alignment()) &amp;&amp; !from.HasPointers():
        return "convT64", types.Types[types.TUINT64], false
    }

    .............
    if from.HasPointers() {
        return "convT", types.Types[types.TUNSAFEPTR], true
    }
    return "convTnoptr", types.Types[types.TUNSAFEPTR], true
}

// convT converts a value of type t, which is pointed to by v, to a pointer that can
// be used as the second word of an interface value.
func convT(t *_type, elem unsafe.Pointer) (e eface) {
    .....
    x := mallocgc(t.size, t, true)  // 空间的分配
    typedmemmove(t, x, elem)                // memove
    e._type = t
    e.data = x
    return
}

很多对 interface 类型的赋值(并非所有),都会导致空间的分配和拷贝,这也是 Interface 函数为什么可能会导致逃逸的原因 go 这么做的主要原因:逃逸的分析位于编译阶段,对于不确定的类型在堆上分配最为合适。

3.1.2 Reflect.Value

go 中 reflect 机制涉及到 2 个类型,reflect.Type 和 reflect.Value,reflect.Type 是一个 Interface,其不在本章介绍范围内。

reflect.Value 定义位于value.gotype.go,其定义与 eface 类似:

type Value struct {
    typ *rtype  // type._type
    ptr unsafe.Pointer
    flag
}

// rtype must be kept in sync with ../runtime/type.go:/^type._type.
type rtype struct {
    ....
}

相似的实现,即为interface和reflect可以相互转换的原因

reflect.Value 是通过 reflect.ValueOf 获得,reflect.ValueOf 也会导致数据逃逸(interface 接口),其定义位于value.go中,如下:

func ValueOf(i interface{}) Value {
    if i == nil {
        return Value{}
    }
    // TODO: Maybe allow contents of a Value to live on the stack.
    // For now we make the contents always escape to the heap.
  // .....
    escapes(i) // 此处没有逃逸
    return unpackEface(i) // 转换eface为emtpyInterface
}

// go1.18中,dummy.b没有赋值操作
func escapes(x any) {
    if dummy.b {
        dummy.x = x
    }
}

reflect.ValueOf 仍然会导致逃逸,但其逃逸还是由 interface 的入参导致

一个简单的例子:

func main() {
    var x = "xxxx"
    _ = reflect.ValueOf(x)
}

结果如下:

➜  gotest666 go build -gcflags=-m main.go
# command-line-arguments
./main.go:26:21: inlining call to reflect.ValueOf
./main.go:26:21: inlining call to reflect.escapes
./main.go:26:21: inlining call to reflect.unpackEface
./main.go:26:21: inlining call to reflect.(*rtype).Kind
./main.go:26:21: inlining call to reflect.ifaceIndir
./main.go:26:22: x escapes to heap

需要注意,x会逃逸到堆上

3.1.3 类型的选择:interface、强类型如何选

为降低不必要的空间分配、拷贝,建议只在必要情况下使用 interface、reflect,针对函数定义,测试如下:

type testStruct struct {
    Data [4096]byte
}

func StrongType(t testStruct) {
    t.Data[0] = 1
}

func InterfaceType(ti interface{}) {
    ts := ti.(testStruct)
    ts.Data[0] = 1
}

func BenchmarkTypeStrong(b *testing.B) {
    t := testStruct{}
    t.Data[0] = 2
    for i := 0; i < b.N; i++ {
        StrongType(t)
    }
}

func BenchmarkTypeInterface(b *testing.B) {
    t := testStruct{}
    t.Data[0] = 2
    for i := 0; i < b.N; i++ {
        InterfaceType(t)
    }
}
➜  test go test --bench='Type' -run=none -benchmem
goos: darwin
goarch: amd64
pkg: gotest666/test
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkTypeStrong-12          1000000000           0.2550 ns/op          0 B/op          0 allocs/op
BenchmarkTypeInterface-12        1722150           709.0 ns/op      4096 B/op          1 allocs/op
PASS
ok      gotest666/test  2.714s
需要注意,当入参参数占用空间不大时(比如基础类型),二者性能对比并不十分明显

强类型函数调用性能远优于基于 interface 的调用,优化后 content-service 只使用了少量的 interface。

目前一些常用的基于 interface(可能会导致逃逸)的函数:

函数 功能
fmt 系列,包括:fmt.Sprinf、fmt.Sprint 等 数据转换、格式处理
binary.Read/binary.Write 二级制数据读写
json.Marshal/json.Unmarshal json 的序列化、反序列化
3.1.4 类型转换: 强转 vs 断言 vs reflect

目前 go 中数据类型转换,存在以下几种方式:

  1. 强转,如 int 转 int64,可用 int64(intData)。强转是对底层数据进行语意上的重新解释
  2. 断言(interface),根据已有信息,对变量类型进行断言,如 interfaceData.(int64),会利用 eface.type 中相关信息,对类型进行校验、转换。
  3. reflect 相关函数,如 reflect.Valueof(intData).Int(),其中 intData 可以为各种 int 相关类型,具有较大的灵活性。

针对此的测试如下:

type testStruct struct {
    Data [4096]byte
}

func BenchmarkConvertForce(b *testing.B) {
    for i := 0; i < b.N; i++ {
        var v = int32(64)
        f := int64(v)
        if f != int64(64) {
            b.Error("errror")
        }
    }
}

func BenchmarkConvertReflect(b *testing.B) {
    for i := 0; i < b.N; i++ {
        var v = int32(64)
        f := reflect.ValueOf(v).Int()
        if f != int64(64) {
            b.Error("errror")
        }
    }
}

func BenchmarkConvertAssert(b *testing.B) {
    for i := 0; i < b.N; i++ {
        var v interface{} = int32(64)
        f := v.(int32)
        if f != int32(64) {
            b.Error("error")
        }
    }
}
➜  test go test --bench='Convert' -run=none -benchmem -gcflags=all=-l
goos: darwin
goarch: amd64
pkg: gotest666/test
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkConvertForce-12            1000000000           0.2843 ns/op          0 B/op          0 allocs/op
BenchmarkConvertReflect-12          84957760            13.66 ns/op        0 B/op          0 allocs/op
BenchmarkConvertAssert-12           1000000000           0.2586 ns/op          0 B/op      

可以看出性能上:强类型转换/assert>reflect 没有逃逸的原因参见:iface.go

content-service 中已经不再使用 reflect 相关的转换处理

3.2 常用 map

go 中常用的 map 包含,runtime.map、sync.map 和第三方的 ConcurrentMap,go 中 map 的定义位于map.go,典型的基于 bucket 的 map 的实现,如下:

type hmap struct {
    ......
    B         uint8  // log_2 of # of buckets (can hold up to loadFactor * 2^B items)
    hash0     uint32 // hash seed

    buckets    unsafe.Pointer // array of 2^B Buckets. may be nil if count==0.
    oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing
  ......
}

其查找、删除、rehash 机制参见https://juejin.cn/post/7056290831182856205

sync.map 定义位于map.go中,其是典型的以空间换时间的处理,具体如下:

type readOnly struct {
    m       map[interface{}]*entry
    amended bool // true if the dirty map contains some key not in m.
}

type entry struct {
    p unsafe.Pointer // *interface{}
}

type Map struct {
    mu Mutex
    read atomic.Value // readOnly数据
    dirty map[interface{}]*entry
    misses int
}

read 中存储的是 dirty 数据的一个副本(通过指针),在读多写少的情况下,基本可以实现无锁的数据读取。

Sync.map 相关机制参见:https://juejin.cn/post/6844903895227957262

go 中还有一个第三方的 ConcurrentMap,其采用分段锁的原理,通过降低锁的粒度提升性能,参见:current-map

针对 map、sync.map、ConcurrentMap 的测试如下:

const mapCnt = 20
func BenchmarkStdMapGetSet(b *testing.B) {
    mp := map[string]string{}
    keys := []string{"a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r"}
    for i := range keys {
        mp[keys[i]] = keys[i]
    }
    var m sync.Mutex
    b.ResetTimer()
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            for i := 0; i < mapCnt; i++ {
                for j := range keys {
                    m.Lock()
                    _ = mp[keys[j]]
                    m.Unlock()
                }
            }

            m.Lock()
            mp["d"] = "d"
            m.Unlock()
        }
    })
}

func BenchmarkSyncMapGetSet(b *testing.B) {
    var mp sync.Map
    keys := []string{"a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r"}
    for i := range keys {
        mp.Store(keys[i], keys[i])
    }
    b.ResetTimer()
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            for i := 0; i < mapCnt; i++ {
                for j := range keys {
                    _, _ = mp.Load(keys[j])
                }
            }

            mp.Store("d", "d")
        }
    })
}

func BenchmarkConcurrentMapGetSet(b *testing.B) {
    m := cmap.New[string]()
    keys := []string{"a", "b", "c", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r"}
    for i := range keys {
        m.Set(keys[i], keys[i])
    }
    b.ResetTimer()
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            for i := 0; i < mapCnt; i++ {
                for j := range keys {
                    _, _ = m.Get(keys[j])
                }
            }

            m.Set("d", "d")
        }
    })
}
➜  test go test --bench='GetSet' -run=none -benchmem
goos: darwin
goarch: amd64
pkg: gotest666/test
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkStdMapGetSet-12               49065         24976 ns/op           0 B/op          0 allocs/op
BenchmarkSyncMapGetSet-12             722704          1756 ns/op          16 B/op          1 allocs/op
BenchmarkConcurrentMapGetSet-12       227001          5206 ns/op           0 B/op          0 allocs/op
PASS

需要注意此测试,读写并发比 20:1 读多写少,建议使用 sync.Map。如果业务场景中,很明确只有对 map 的读操作,建议使用 runtime.Map

目前 content-service 中 runtime.map、sync.map 都有涉及

3.3 hash 的实现: index vs map

在使用到 hash 的场景,除了 map,我们还可以基于 slice 或者数组的索引,content-service 基于此实现另外一种 map。其性能对比如下:

func BenchmarkHashIdx(b *testing.B) {
    var data = [10]int{0: 1, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
    for i := 0; i < b.N; i++ {
        tmp := data[b.N%10]
        _ = tmp
    }
}
func BenchmarkHashMap(b *testing.B) {
    var data = map[int]int{0: 1, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
    for i := 0; i < b.N; i++ {
        tmp := data[b.N%10]
        _ = tmp
    }
}
➜  test go test --bench='Hash' -run=none -benchmem
goos: darwin
goarch: amd64
pkg: gotest666/test
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkHashIdx-12     1000000000           1.003 ns/op           0 B/op          0 allocs/op
BenchmarkHashMap-12     196543544            7.665 ns/op           0 B/op          0 allocs/op
PASS

性能有 5 倍左右提升,content-service 在解析正排数据时,即采用此种处理。

3.4 string 和 slice

3.4.1 string 和 slice 的定义

在 go 中 string、slice 都是基于 buf、len 的定义,二者定义都位于value.go中:

type StringHeader struct
    Data uintptr
    Len  int
}

type SliceHeader struct {
    Data uintptr
    Len  int
    Cap  int
}

通过二者定义可以得出:

  1. 在值拷贝背景下,string、slice 的赋值操作代价都不大,最多有 24Byte
  2. slice 因为涉及到 cap,会涉及到预分配、惰性删除,其具体位于slice.go
3.4.2 String、[]byte 转换

go 中 string 和[]byte 间相互转换包含 2 种:

  1. 采用原生机制,比如 string 转 slice 可采用,[]byte(strData)
  2. 基于对底层数据结构重新解释

以 string 转换为 byte 为例,原生转换的转换会进行如下操作,其位于string.go中:

func stringtoslicebyte(buf *tmpBuf, s string) []byte {
    var b []byte
    if buf != nil &amp;&amp; len(s) <= len(buf) { // 如果可以在tmpBuf中保存
        *buf = tmpBuf{}
        b = buf[:len(s)]
    } else {
        b = rawbyteslice(len(s)) // 如果32字节不够存储数据,则调用mallocgc分配空间
    }
    copy(b, s)  // 数据拷贝
    return b
}

// rawbyteslice allocates a new byte slice. The byte slice is not zeroed.
func rawbyteslice(size int) (b []byte) {
    cap := roundupsize(uintptr(size))
    p := mallocgc(cap, nil, false)  // 空间分配
    if cap != uintptr(size) {
        memclrNoHeapPointers(add(p, uintptr(size)), cap-uintptr(size))
    }

    *(*slice)(unsafe.Pointer(&amp;b)) = slice{p, size, int(cap)}
    return
}

其中 tmpBuf 定义为 type tmpBuf [32]byte。 当长度超过 32 字节时,会进行空间的分配、拷贝

同理,byte 转换为 string,原生处理位于 slicebytetostring 函数,也位于string.go

针对多余的空间分配、拷贝问题,content-service 对此进行了封装,具体参见tools.go,该实现通过对底层数据重新解释进行,具有较高的效率。

以 byteToString 为例,相关 benchMark 如下:

func BenchmarkByteToStringRaw(b *testing.B) {
   bytes := getByte(34)
   b.ResetTimer()
   for i := 0; i < b.N; i++ {
      v := string(bytes)
      if len(v) <= 0 {
         b.Error("error")
      }
   }
}
// 认为对底层数据进行重新解释
func Bytes2String(b []byte) string {
   x := (*[3]uintptr)(unsafe.Pointer(&amp;b))
   s := [2]uintptr{x[0], x[1]}
   return *(*string)(unsafe.Pointer(&amp;s))
}

func BenchmarkByteToStringPointer(b *testing.B) {
   bytes := getByte(34)
   b.ResetTimer()
   for i := 0; i < b.N; i++ {
      v := Bytes2String(bytes)
      if len(v) <= 0 {
         b.Error("error")
      }
   }
}
➜  gotest666 go test --bench='ByteToString' -run=none -benchmem
goos: darwin
goarch: amd64
pkg: gotest666
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkByteToStringRaw-12         47646651            23.37 ns/op       48 B/op          1 allocs/op
BenchmarkByteToStringPointer-12     1000000000           0.7539 ns/op          0 B/op          0 allocs/op

其性能有较大提升,性能提升的主要原因,0 gc 0拷贝需要注意,本处理只针对转换,不涉及 append 等可能引起扩容的处理

3.4.3 string 的拼接

当前 golang 中字符串拼接方式,主要包含:

  1. 使用+连接字符串
  2. 使用 fmt.Sprintf
  3. 使用运行时工具类,strings.Builder 或者 bytes.Buffer
  4. 预分配机制

目前对+的处理,其处理函数位于string.go,当要连接的字符串长度>32 时,每次会进行空间的分配和拷贝处理,其处理如下:

func concatstrings(buf *tmpBuf, a []string) string {
    idx := 0
    l := 0
    count := 0
    for i, x := range a {  // 计算+链接字符的长度
        n := len(x)
        if n == 0 {
            continue
        }
        if l+n < l {
            throw("string concatenation too long")
        }
        l += n
        count++
        idx = i
    }
    if count == 0 {
        return ""
    }
    .....
  s, b := rawstringtmp(buf, l) // 如果长度小于len(buf)(32),则分配空间,否则使用buf
    for _, x := range a {
        copy(b, x)
        b = b[len(x):]
    }
    return s
}

type tmpBuf [32]byte

fmt.Sprinf,涉及大量的 interface 相关操作,会导致逃逸。

针对+、fmt.Sprintf 等的对比测试如下:

func BenchmarkStringJoinAdd(b *testing.B) {
   var s string
   for i := 0; i < b.N; i++ {
      for i := 0; i < count; i++ {
         s += "10"
      }
   }
}

func BenchmarkStringJoinSprintf(b *testing.B) {
   var s string
   for i := 0; i < b.N; i++ {
      for i := 0; i < count; i++ {
         s = fmt.Sprintf("%s%s", s, "10")
      }
   }
}

func BenchmarkStringJoinStringBuilder(b *testing.B) {
   var sb strings.Builder
   sb.Grow(count * 2) // 预分配了空间
   b.ResetTimer()

   for i := 0; i < b.N; i++ {
      for i := 0; i < count; i++ {
         sb.WriteString("10")
      }
   }
}
➜  gotest666 go test --bench='StringJoin' -run=none -benchmem
goos: darwin
goarch: amd64
pkg: gotest666
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkStringJoinAdd-12                    124      11992891 ns/op    127697864 B/op      1006 allocs/op
BenchmarkStringJoinSprintf-12                100      19413234 ns/op    195832744 B/op      2808 allocs/op
BenchmarkStringJoinStringBuilder-12       189568          7335 ns/op       12392 B/op          0 allocs/op

可以看出,空间预分配拥有非常高的性能指标。目前,Content-service 中都采用了空间预分配的方式,其他的一些测试参见:string 连接

3.5 循环的处理: for vs range

go 中常用的循环有 2 种 for 和 range,如下:

  1. 按位置进行遍历,for 和 range 都支持,如 for i:=range a{}, for i:=0;i<len(a);i++
  2. 同时对位置、值进行遍历,range 支持,如 for i,v := range a {}

go 中循环经过一系列的编译、优化后,伪代码如下:

ta := a     // 容器的拷贝
i := 0
l := len(ta) // 获取长度
for ; i < l; i++ {
    v := ta[i]  // 容器中元素的拷贝
}

此处理可能会导致以下问题:

  1. 遍历前,会进行值的拷贝,如果是数组,会有大量数据拷贝,slice 和 map 等引用的拷贝较少
  2. for range value 在遍历中存在对容器元素的拷贝
  3. 遍历开始,已经确定了容器长度,中间添加的数据,不会遍历到

针对此测试如下:

type Item struct {
    id  int
    val [4096]byte
}

func BenchmarkLoopFor(b *testing.B) {
    var items [1024]Item
    for i := 0; i < b.N; i++ {
        length := len(items)
        var tmp int
        for k := 0; k < length; k++ {
            tmp = items[k].id
        }
        _ = tmp
    }
}

func BenchmarkLoopRangeIndex(b *testing.B) {
    var items [1024]Item
    for i := 0; i < b.N; i++ {
        var tmp int
        for k := range items {
            tmp = items[k].id
        }
        _ = tmp
    }
}

func BenchmarkLoopRangeValue(b *testing.B) {
    var items [1024]Item
    for i := 0; i < b.N; i++ {
        var tmp int
        for _, item := range items {
            tmp = item.id
        }
        _ = tmp
    }
}
➜  test go test --bench='Loop' -run=none -benchmem
goos: darwin
goarch: amd64
pkg: gotest666/test
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkLoopFor-12              4334842           270.8 ns/op         0 B/op          0 allocs/op
BenchmarkLoopRangeIndex-12       4436786           272.7 ns/op         0 B/op          0 allocs/op
BenchmarkLoopRangeValue-12          7310        211009 ns/op           0 B/op          0 allocs/op
PASS

注意,对于所需空间较小,如指针类型数组等此问题并不严重 在需要较大存储空间、元素需要较大存储空间时,建议不要采用 range value 的方式

content_service 中目前基本都是基于 for index、range index 的处理

3.6 重载

目前 go 中重载的实现包含 2 种,泛型(1.18)、基于 interface 的定义。泛型的优点在于预编译,即编译期间即可确定类型,对比基于 interface 的逃逸会有一定收益,具体测试如下:

func AddGeneric[T int | int16 | int32 | int64](a, b T) T {
    return a + b
}

func AddInterface(a, b interface{}) interface{} {
    switch a.(type) {
    case int:
        return a.(int) + b.(int)
    case int32:
        return a.(int32) + b.(int32)
    case int64:
        return a.(int64) + b.(int64)
    }
    return 0
}

func BenchmarkOverLoadGeneric(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x := AddGeneric(i, i)
        _ = x
    }
}
func BenchmarkOverLoadInterface(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x := AddInterface(i, i)
        _ = x.(int)
    }
}
➜  test go test --bench='OverLoad' -run=none -benchmem
goos: darwin
goarch: amd64
pkg: gotest666/test
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkOverLoadGeneric-12         1000000000           0.2778 ns/op          0 B/op          0 allocs/op
BenchmarkOverLoadInterface-12       954258690            1.248 ns/op           0 B/op          0 allocs/op
PASS

对比 interface 类型的处理,泛型有一定的性能的提升,目前在 content-service 中已经得到了大量的使用。

4 空间与布局

4.1 栈与堆空间的分配

在栈上分配空间为什么会比堆上快?

通过汇编,可观察栈空间分配机制,如下:

package main

func test(a, b int) int {
    return a + b
}

其对应汇编代码如下:

main.test STEXT nosplit size=49 args=0x10 locals=0x10 funcid=0x0 align=0x0
        0x0000 00000 (/Users/zhangyuxin/go/src/gotest666/test.go:3)     TEXT    main.test(SB), NOSPLIT|ABIInternal, $16-16
        0x0000 00000 (/Users/zhangyuxin/go/src/gotest666/test.go:3)     SUBQ    $16, SP         // 栈扩容
                ......
        0x002c 00044 (/Users/zhangyuxin/go/src/gotest666/test.go:4)     ADDQ    $16, SP         // 栈释放
        0x0030 00048 (/Users/zhangyuxin/go/src/gotest666/test.go:4)     RET

在 go 中栈的扩容、释放只涉及到了 SUBQ、ADDQ 2 条指令。

对应的基于堆的内存分配,位于malloc.go中 mallocgc 函数,p 的定义、mheap 的定义分别位于runtime2.gomcache.gomheap.go,其分配流程具体如下(<32K, >8B):

其中,直接从 p.mcache 获取空间不需要加锁(单协程),mheap.mcentral 获取空间需要加锁(全局变量)、mmap 需要系统调用。此外,堆上分配还需要考虑 gc 导致的 stw 等的影响,因此建议所需空间不是特别大时还是在栈上进行空间的分配。

content-service 开发中有一个共识: 能在栈上处理的数据,不会放到堆上。

4.2 Zero GC

Zero GC 能够避免 gc 带来的扫描、STW 等,具有一定的性能收益。

当前 zero gc 的处理,主要包含 2 种:

  1. 无 gc,通过 mmap 或者 cgo.malloc 分配空间,绕过 go 的内存分配机制,如 fastcache 的实现
  2. 避免或者减少 gc,通过[]byte 等避免因为指针导致的扫描、stw,bigCache 的实现即为此。

Zero GC 的优点在于,避免了 go gc 处理带来的标记扫描、STW 等,相对于常规堆上数据分配,其性能有较大提升。content-service 在重构中,使用了大量的基于 0 gc 的库,比如 fastcache,对一些常用函数、机制,如 strings.split 也进行了 0 gc 的优化,其实现如下:

在 content-service 中其实现位于string_util.go,如下:

type StringSplitter struct {
    Idx [8]int  // 存储splitter对应的位置信息
    src string
    cnt int
}

// Split 分割
func (s *StringSplitter) Split(str string, sep byte) bool {
    s.src = str
    for i := 0; i < len(str); i++ {
        if str[i] == sep {
            s.Idx[s.cnt] = i
            s.cnt++

            // 超过Idx数据长度则返回空
            if int(s.cnt) >= len(s.Idx) {
                return false
            }
        }
    }

    return true
}

与常规 strings.split 对比如下,其性能有近 4 倍左右提升:

➜  test go test --bench='Split' -run=none -benchmem
goos: darwin
goarch: amd64
pkg: gotest666/test
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkQSplitRaw-12       13455728            76.43 ns/op       64 B/op          1 allocs/op
BenchmarkQSplit-12          59633916            20.08 ns/op        0 B/op          0 allocs/op
PASS

4.3 GC 的优化

gc 优化相关,主要涉及 GOGC、GOMEMLIMIT,参见:Golang 垃圾回收介绍及参数调整

需要注意,此机制只在 1.20 以上版本生效

4.4 逃逸

对于一些处理比较复杂操作,go 在编译器会在编译期间将相关变量逃逸至堆上。目前可能导致逃逸的机制包含:

  1. 基于指针的逃逸
  2. 栈空间不足,超过了 os 的限制 8M
  3. 闭包
  4. 动态类型

目前逃逸分析,可采用-gcflags=-m 进行查看,如下:

type test1 struct {
    a int32
    b int
    c int32
}

type test2 struct {
    a int32
    c int32
    b int
}

func getData() *int {
    a := 10
    return &amp;a
}

func main() {
    fmt.Println(unsafe.Sizeof(test1{}))
    fmt.Println(unsafe.Sizeof(test2{}))
    getData()
}
➜  gotest666 go build -gcflags=-m main.go
# command-line-arguments
./main.go:20:6: can inline getData
./main.go:26:13: inlining call to fmt.Println
./main.go:27:13: inlining call to fmt.Println
./main.go:28:9: inlining call to getData
./main.go:21:2: moved to heap: a        // 返回指针导致逃逸
./main.go:26:13: ... argument does not escape
./main.go:26:27: unsafe.Sizeof(test1{}) escapes to heap // 动态类型导致逃逸
./main.go:27:13: ... argument does not escape
./main.go:27:27: unsafe.Sizeof(test2{}) escapes to heap // 动态类型导致逃逸

在日常业务处理过程中,建议尽量避免逃逸到堆上的情况

4.5 数据的对齐

go 中同样存在数据对齐,适当的布局调整,能够节省大量的空间,具体如下:

type test1 struct {
    a int32
    b int
    c int32
}

type test2 struct {
    a int32
    c int32
    b int
}

func main() {
    fmt.Println(unsafe.Alignof(test1{}))
    fmt.Println(unsafe.Alignof(test2{}))
    fmt.Println(unsafe.Sizeof(test1{}))
    fmt.Println(unsafe.Sizeof(test2{}))
}
➜  gotest666 go run main.go
8
8
24
16

4.6 空间预分配

空间预分配,可以避免大量不必要的空间分配、拷贝,目前 slice、map、strings.Builder、byte.Builder 等都涉及到预分配机制。

以 map 为例,测试结果如下:

func BenchmarkConcurrentMapAlloc(b *testing.B) {
    m := map[int]int{}
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        m[i] = i
    }
}

func BenchmarkConcurrentMapPreAlloc(b *testing.B) {
    m := make(map[int]int, b.N)
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        m[i] = i
    }
}
➜  test go test --bench='Alloc' -run=none -benchmem
goos: darwin
goarch: amd64
pkg: gotest666/test
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkConcurrentMapAlloc-12           6027334           186.0 ns/op        60 B/op          0 allocs/op
BenchmarkConcurrentMapPreAlloc-12       15499568            89.68 ns/op        0 B/op          0 allocs/op
PASS

预分配能够极大提升,相关性能, 建议在使用时都进行空间的预分配。content-service 在开发中基本都做到了空间的预分配。

5 并发编程

5.1 锁

golang 中 mutex 定义位于mutex.go,其定义如下:

type Mutex struct {
    state int32         // 状态字,标识锁是否被锁定、是否starving等
    sema  uint32        // 信号量
}

golang 的读写锁基于 mutex,其定义位于rwmutex.go, 其定义如下:

type RWMutex struct {
    w           Mutex  // 用于阻塞写协程
    writerSem   uint32 // 写信号量,用于实现写阻塞队列
    readerSem   uint32 // 读信号量,用于实现读阻塞队列
    readerCount int32  // 当前正在读操作的个数
    readerWait  int32  // 防止写操作被饿死,标记排在写操作前读操作的个数
}

RWMutex 基于 Mutex 实现,在加写锁上,RWMutex 性能略差于 Mutex。但在读操作较多情况下,RWMutex 性能是优于 Mutex 的,因为 RWMutex 对于读的操作只是通过 readerCount 计数进行, 其相关处理位于rwmutex.go,如下:

func (rw *RWMutex) RLock() {
    if race.Enabled {
        _ = rw.w.state
        race.Disable()
    }
    if rw.readerCount.Add(1) < 0 {  // readCount < 0,表示有写操作正在进行
        runtime_SemacquireRWMutexR(&amp;rw.readerSem, false, 0)
    }
    if race.Enabled {
        race.Enable()
        race.Acquire(unsafe.Pointer(&amp;rw.readerSem))
    }
}

func (rw *RWMutex) Lock() {
    if race.Enabled {
        _ = rw.w.state
        race.Disable()
    }

    rw.w.Lock()                                                                         // 加写锁
    r := rw.readerCount.Add(-rwmutexMaxReaders) + rwmutexMaxReaders // 统计当前读操作的个数,
    if r != 0 &amp;&amp; rw.readerWait.Add(r) != 0 {                                                // 并等待读操作
        runtime_SemacquireRWMutex(&amp;rw.writerSem, false, 0)
    }
    if race.Enabled {
        race.Enable()
        race.Acquire(unsafe.Pointer(&amp;rw.readerSem))
        race.Acquire(unsafe.Pointer(&amp;rw.writerSem))
    }
}

按照读写比例的不同,进行了如下测试:

var mut sync.Mutex
var rwMut sync.RWMutex
var t int

const cost = time.Microsecond

func WRead() {
    mut.Lock()
    _ = t
    time.Sleep(cost)
    mut.Unlock()
}

func WWrite() {
    mut.Lock()
    t++
    time.Sleep(cost)
    mut.Unlock()
}

func RWRead() {
    rwMut.RLock()
    _ = t
    time.Sleep(cost)
    rwMut.RUnlock()
}

func RWWrite() {
    rwMut.Lock()
    t++
    time.Sleep(cost)
    rwMut.Unlock()
}

func benchmark(b *testing.B, readFunc, writeFunc func(), read, write int) {
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            var wg sync.WaitGroup
            for k := 0; k < read*100; k++ {
                wg.Add(1)
                go func() {
                    readFunc()
                    wg.Done()
                }()
            }
            for k := 0; k < write*100; k++ {
                wg.Add(1)
                go func() {
                    writeFunc()
                    wg.Done()
                }()
            }
            wg.Wait()
        }
    })
}

func BenchmarkReadMore(b *testing.B)         { benchmark(b, WRead, WWrite, 9, 1) }
func BenchmarkReadMoreRW(b *testing.B)       { benchmark(b, RWRead, RWWrite, 9, 1) }
func BenchmarkWriteMore(b *testing.B)        { benchmark(b, WRead, WWrite, 1, 9) }
func BenchmarkWriteMoreRW(b *testing.B)      { benchmark(b, RWRead, RWWrite, 1, 9) }
func BenchmarkReadWriteEqual(b *testing.B)   { benchmark(b, WRead, WWrite, 5, 5) }
func BenchmarkReadWriteEqualRW(b *testing.B) { benchmark(b, RWRead, RWWrite, 5, 5) }
➜  test go test --bench='Read|Write' -run=none -benchmem
goos: darwin
goarch: amd64
pkg: gotest666/test
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkReadMore-12                     207       5713542 ns/op      114190 B/op       2086 allocs/op
BenchmarkReadMoreRW-12                  1237        904307 ns/op      104683 B/op       2007 allocs/op
BenchmarkWriteMore-12                    211       5799927 ns/op      110360 B/op       2067 allocs/op
BenchmarkWriteMoreRW-12                  222       5490282 ns/op      110666 B/op       2070 allocs/op
BenchmarkReadWriteEqual-12               213       5752311 ns/op      111017 B/op       2065 allocs/op
BenchmarkReadWriteEqualRW-12             386       3088603 ns/op      106810 B/op       2030 allocs/op

在读写比例为 9:1 时,RWMute 性能约为 Mutex 的 6 倍。

6. 其他

需要注意:语言层面只能解决单点的性能问题,良好的架构设计才能从全局解决问题

本文所有 benchmark、源码都是基于 1.18。

7. 参考资料

本文由微信公众号腾讯技术工程原创,哈喽比特收录。
文章来源:https://mp.weixin.qq.com/s/VMzhyySny60zABnxlzlVjQ

 相关推荐

刘强东夫妇:“移民美国”传言被驳斥

京东创始人刘强东和其妻子章泽天最近成为了互联网舆论关注的焦点。有关他们“移民美国”和在美国购买豪宅的传言在互联网上广泛传播。然而,京东官方通过微博发言人发布的消息澄清了这些传言,称这些言论纯属虚假信息和蓄意捏造。

发布于:7月以前  |  808次阅读  |  详细内容 »

博主曝三大运营商,将集体采购百万台华为Mate60系列

日前,据博主“@超能数码君老周”爆料,国内三大运营商中国移动、中国电信和中国联通预计将集体采购百万台规模的华为Mate60系列手机。

发布于:7月以前  |  770次阅读  |  详细内容 »

ASML CEO警告:出口管制不是可行做法,不要“逼迫中国大陆创新”

据报道,荷兰半导体设备公司ASML正看到美国对华遏制政策的负面影响。阿斯麦(ASML)CEO彼得·温宁克在一档电视节目中分享了他对中国大陆问题以及该公司面临的出口管制和保护主义的看法。彼得曾在多个场合表达了他对出口管制以及中荷经济关系的担忧。

发布于:7月以前  |  756次阅读  |  详细内容 »

抖音中长视频App青桃更名抖音精选,字节再发力对抗B站

今年早些时候,抖音悄然上线了一款名为“青桃”的 App,Slogan 为“看见你的热爱”,根据应用介绍可知,“青桃”是一个属于年轻人的兴趣知识视频平台,由抖音官方出品的中长视频关联版本,整体风格有些类似B站。

发布于:7月以前  |  648次阅读  |  详细内容 »

威马CDO:中国每百户家庭仅17户有车

日前,威马汽车首席数据官梅松林转发了一份“世界各国地区拥车率排行榜”,同时,他发文表示:中国汽车普及率低于非洲国家尼日利亚,每百户家庭仅17户有车。意大利世界排名第一,每十户中九户有车。

发布于:7月以前  |  589次阅读  |  详细内容 »

研究发现维生素 C 等抗氧化剂会刺激癌症生长和转移

近日,一项新的研究发现,维生素 C 和 E 等抗氧化剂会激活一种机制,刺激癌症肿瘤中新血管的生长,帮助它们生长和扩散。

发布于:7月以前  |  449次阅读  |  详细内容 »

苹果据称正引入3D打印技术,用以生产智能手表的钢质底盘

据媒体援引消息人士报道,苹果公司正在测试使用3D打印技术来生产其智能手表的钢质底盘。消息传出后,3D系统一度大涨超10%,不过截至周三收盘,该股涨幅回落至2%以内。

发布于:8月以前  |  446次阅读  |  详细内容 »

千万级抖音网红秀才账号被封禁

9月2日,坐拥千万粉丝的网红主播“秀才”账号被封禁,在社交媒体平台上引发热议。平台相关负责人表示,“秀才”账号违反平台相关规定,已封禁。据知情人士透露,秀才近期被举报存在违法行为,这可能是他被封禁的部分原因。据悉,“秀才”年龄39岁,是安徽省亳州市蒙城县人,抖音网红,粉丝数量超1200万。他曾被称为“中老年...

发布于:7月以前  |  445次阅读  |  详细内容 »

亚马逊股东起诉公司和贝索斯,称其在购买卫星发射服务时忽视了 SpaceX

9月3日消息,亚马逊的一些股东,包括持有该公司股票的一家养老基金,日前对亚马逊、其创始人贝索斯和其董事会提起诉讼,指控他们在为 Project Kuiper 卫星星座项目购买发射服务时“违反了信义义务”。

发布于:7月以前  |  444次阅读  |  详细内容 »

苹果上线AppsbyApple网站,以推广自家应用程序

据消息,为推广自家应用,苹果现推出了一个名为“Apps by Apple”的网站,展示了苹果为旗下产品(如 iPhone、iPad、Apple Watch、Mac 和 Apple TV)开发的各种应用程序。

发布于:7月以前  |  442次阅读  |  详细内容 »

特斯拉美国降价引发投资者不满:“这是短期麻醉剂”

特斯拉本周在美国大幅下调Model S和X售价,引发了该公司一些最坚定支持者的不满。知名特斯拉多头、未来基金(Future Fund)管理合伙人加里·布莱克发帖称,降价是一种“短期麻醉剂”,会让潜在客户等待进一步降价。

发布于:7月以前  |  441次阅读  |  详细内容 »

光刻机巨头阿斯麦:拿到许可,继续对华出口

据外媒9月2日报道,荷兰半导体设备制造商阿斯麦称,尽管荷兰政府颁布的半导体设备出口管制新规9月正式生效,但该公司已获得在2023年底以前向中国运送受限制芯片制造机器的许可。

发布于:7月以前  |  437次阅读  |  详细内容 »

马斯克与库克首次隔空合作:为苹果提供卫星服务

近日,根据美国证券交易委员会的文件显示,苹果卫星服务提供商 Globalstar 近期向马斯克旗下的 SpaceX 支付 6400 万美元(约 4.65 亿元人民币)。用于在 2023-2025 年期间,发射卫星,进一步扩展苹果 iPhone 系列的 SOS 卫星服务。

发布于:7月以前  |  430次阅读  |  详细内容 »

𝕏(推特)调整隐私政策,可拿用户发布的信息训练 AI 模型

据报道,马斯克旗下社交平台𝕏(推特)日前调整了隐私政策,允许 𝕏 使用用户发布的信息来训练其人工智能(AI)模型。新的隐私政策将于 9 月 29 日生效。新政策规定,𝕏可能会使用所收集到的平台信息和公开可用的信息,来帮助训练 𝕏 的机器学习或人工智能模型。

发布于:7月以前  |  428次阅读  |  详细内容 »

荣耀CEO谈华为手机回归:替老同事们高兴,对行业也是好事

9月2日,荣耀CEO赵明在采访中谈及华为手机回归时表示,替老同事们高兴,觉得手机行业,由于华为的回归,让竞争充满了更多的可能性和更多的魅力,对行业来说也是件好事。

发布于:7月以前  |  423次阅读  |  详细内容 »

AI操控无人机能力超越人类冠军

《自然》30日发表的一篇论文报道了一个名为Swift的人工智能(AI)系统,该系统驾驶无人机的能力可在真实世界中一对一冠军赛里战胜人类对手。

发布于:8月以前  |  423次阅读  |  详细内容 »

AI生成的蘑菇科普书存在可致命错误

近日,非营利组织纽约真菌学会(NYMS)发出警告,表示亚马逊为代表的电商平台上,充斥着各种AI生成的蘑菇觅食科普书籍,其中存在诸多错误。

发布于:8月以前  |  420次阅读  |  详细内容 »

社交媒体平台𝕏计划收集用户生物识别数据与工作教育经历

社交媒体平台𝕏(原推特)新隐私政策提到:“在您同意的情况下,我们可能出于安全、安保和身份识别目的收集和使用您的生物识别信息。”

发布于:8月以前  |  411次阅读  |  详细内容 »

国产扫地机器人热销欧洲,国产割草机器人抢占欧洲草坪

2023年德国柏林消费电子展上,各大企业都带来了最新的理念和产品,而高端化、本土化的中国产品正在不断吸引欧洲等国际市场的目光。

发布于:7月以前  |  406次阅读  |  详细内容 »

罗永浩吐槽iPhone15和14不会有区别,除了序列号变了

罗永浩日前在直播中吐槽苹果即将推出的 iPhone 新品,具体内容为:“以我对我‘子公司’的了解,我认为 iPhone 15 跟 iPhone 14 不会有什么区别的,除了序(列)号变了,这个‘不要脸’的东西,这个‘臭厨子’。

发布于:7月以前  |  398次阅读  |  详细内容 »
 相关文章
Android插件化方案 5年以前  |  236876次阅读
vscode超好用的代码书签插件Bookmarks 1年以前  |  6902次阅读
 目录