美文网首页
go语言的slice和redis的SDS对比

go语言的slice和redis的SDS对比

作者: golang推广大使 | 来源:发表于2020-04-27 14:51 被阅读0次

为什么要拿Redis的SDS与golang的切片进行对比

之所以拿这两个做对比,是因为觉得他们在设计上有些异曲同工之处。比如:

  • 两者求取长度的复杂度都是O(1)
  • 两者求取容量的复杂度也是O(1)
  • 两者扩容时都采用了于扩容的策略,避免频繁申请内存
  • 两者缩容时也都不会立刻释放多余的内存

下面我们就拿这两个做一下对比。
首先,我们看一下Redis中SDS。

struct sdshdr {
    //记录buf数组中已使用的字节的数量
    //等于SDS所保存的字符串长度
    int len;
    //记录buf数组中未使用字节的数量
    int free;
    //字节数组,用于保存字符串
    char buf[];
}

一个free至和len值都是5,保存有『Redis』的字符串的SDS的结构的示例如下:


image.png

上图中有5个字节的未使用空间。
我们再看看golang中切片的定义

type slice struct {
    array unsafe.Pointer //引用切片底层的数组
    len int //用于限定可读写的元素数量
    cap int //表示切片所引用的数组的真实长度
}

我们暂且放下golang中slice元素可以是任何类型的的区别,看看他们的异同。
假定切片slice1是个字节切片,那么slice中array就是一个指向字节数组的指针。

  • 在Redis的SDS设计中,要获得SDS的长度,用len属性即可;在slice中同样也是如此。
  • SDS中获取容量,用free+len即可获得; 在slice中获取slice的容量,可以用cap属性
  • 如果对SDS进行修改之后,SDS的长度(也即是len属性的值)将小于1MB,那么程序分配和len属性同样大小的未使用空间,这时SDS len属性的值将和free属性的值相同。举个例子,如果进行修改之后,SDS的len将变成13字节,那么程序也会分配13字节的未使用空间,SDS的buf数组的实际长度将变成13+13+1=27字节(额外的一字节用于保存空字符),果对SDS进行修改之后,SDS的长度将大于等于1MB,那么程序会分配1MB的未使用空间。举个例子,如果进行修改之后,SDS的len将变成30MB,那么程序会分配1MB的未使用空间,SDS的buf数组的实际长度将为30MB+1MB+1byte;同样,如果我们对一个golang中的slice执行append操作时发现,当原slice的cap小于1024时,新slice的cap变为原来的2倍;原slice的cap大于1024时,新slice变为原来的1.25倍。
  • 如果SDS存储的字符串要变更为一个比原来短的字符串,程序并不会立刻回收缩短后多出来的字节,而是用free属性将这些自己记录下来; 而go里面与其最相似的操作可能就是slice1=slice1[0:(len(slice)-3)](假定长度大于3,要减少3个),同样go里面也不会释放多余的空间,但是slice的len属性会发生改变。

两者最大的不同在于redis中的SDS只是用于存放字符串。但是golang中的slice则不同,它可以支持各种类型。

但是他们在设计上都减少两种系统调用,向操作系统申请分配内存和释放内存。其实在linux下开发程序,逃不了的都是调用linux系统提供的服务,合理的使用linux系统提供的服务是各种编程语言开发都需要注意的重要事项。

参考:
go里面slice扩容的代码

//runtime/slice.go 
func growslice(et *_type, old slice, cap int) slice {
    if raceenabled {
        callerpc := getcallerpc()
        racereadrangepc(old.array, uintptr(old.len*int(et.size)), callerpc, funcPC(growslice))
    }
    if msanenabled {
        msanread(old.array, uintptr(old.len*int(et.size)))
    }

    if cap < old.cap {
        panic(errorString("growslice: cap out of range"))
    }

    if et.size == 0 {
        // append should not create a slice with nil pointer but non-zero len.
        // We assume that append doesn't need to preserve old.array in this case.
        return slice{unsafe.Pointer(&zerobase), old.len, cap}
    }

    newcap := old.cap //从这里开始看
    doublecap := newcap + newcap
    if cap > doublecap {
        newcap = cap
    } else {
        if old.len < 1024 {
            newcap = doublecap
        } else {
            // Check 0 < newcap to detect overflow
            // and prevent an infinite loop.
            for 0 < newcap && newcap < cap {
                newcap += newcap / 4
            }
            // Set newcap to the requested cap when
            // the newcap calculation overflowed.
            if newcap <= 0 {
                newcap = cap
            }
        }
    }

    var overflow bool
    var lenmem, newlenmem, capmem uintptr
    // Specialize for common values of et.size.
    // For 1 we don't need any division/multiplication.
    // For sys.PtrSize, compiler will optimize division/multiplication into a shift by a constant.
    // For powers of 2, use a variable shift.
    switch {
    case et.size == 1:
        lenmem = uintptr(old.len)
        newlenmem = uintptr(cap)
        capmem = roundupsize(uintptr(newcap))
        overflow = uintptr(newcap) > maxAlloc
        newcap = int(capmem)
    case et.size == sys.PtrSize:
        lenmem = uintptr(old.len) * sys.PtrSize
        newlenmem = uintptr(cap) * sys.PtrSize
        capmem = roundupsize(uintptr(newcap) * sys.PtrSize)
        overflow = uintptr(newcap) > maxAlloc/sys.PtrSize
        newcap = int(capmem / sys.PtrSize)
    case isPowerOfTwo(et.size):
        var shift uintptr
        if sys.PtrSize == 8 {
            // Mask shift for better code generation.
            shift = uintptr(sys.Ctz64(uint64(et.size))) & 63
        } else {
            shift = uintptr(sys.Ctz32(uint32(et.size))) & 31
        }
        lenmem = uintptr(old.len) << shift
        newlenmem = uintptr(cap) << shift
        capmem = roundupsize(uintptr(newcap) << shift)
        overflow = uintptr(newcap) > (maxAlloc >> shift)
        newcap = int(capmem >> shift)
    default:
        lenmem = uintptr(old.len) * et.size
        newlenmem = uintptr(cap) * et.size
        capmem, overflow = math.MulUintptr(et.size, uintptr(newcap))
        capmem = roundupsize(capmem)
        newcap = int(capmem / et.size)
    }

redis里面SDS扩容的代码

sds sdsMakeRoomFor(sds s, size_t addlen) {
    void *sh, *newsh;
    size_t avail = sdsavail(s);
    size_t len, newlen;
    char type, oldtype = s[-1] & SDS_TYPE_MASK;
    int hdrlen;

    /* Return ASAP if there is enough space left. */
    if (avail >= addlen) return s;

    len = sdslen(s);
    sh = (char*)s-sdsHdrSize(oldtype);
    newlen = (len+addlen);//从这里看
    if (newlen < SDS_MAX_PREALLOC) 
        newlen *= 2;
    else
        newlen += SDS_MAX_PREALLOC;

    type = sdsReqType(newlen);

    /* Don't use type 5: the user is appending to the string and type 5 is
     * not able to remember empty space, so sdsMakeRoomFor() must be called
     * at every appending operation. */
    if (type == SDS_TYPE_5) type = SDS_TYPE_8;

    hdrlen = sdsHdrSize(type);
    if (oldtype==type) {
        newsh = s_realloc(sh, hdrlen+newlen+1);
        if (newsh == NULL) return NULL;
        s = (char*)newsh+hdrlen;
    } else {
        /* Since the header size changes, need to move the string forward,
         * and can't use realloc */
        newsh = s_malloc(hdrlen+newlen+1);
        if (newsh == NULL) return NULL;
        memcpy((char*)newsh+hdrlen, s, len+1);
        s_free(sh);
        s = (char*)newsh+hdrlen;
        s[-1] = type;
        sdssetlen(s, len);
    }
    sdssetalloc(s, newlen);
    return s;
}

相关文章

  • go语言的slice和redis的SDS对比

    为什么要拿Redis的SDS与golang的切片进行对比 之所以拿这两个做对比,是因为觉得他们在设计上有些异曲同工...

  • Go语言——Slice分析

    Go语言——Slice分析 源码很不好找,在go\src\runtime\slice.go。 根据容量cap*元素...

  • go语言slice数据类型的定义和使用

    这篇文章介绍go语言slice数据类型的定义,内部格式,以及如何声明和定义slice类型变量。 slice数据类型...

  • Go 语言的 Array 和 Slice

    先抛出几个问题 声明一个 slice 并赋值为 nil, 如 var slice []int = nil,此时 l...

  • Simple Dynamic String (SDS)

    Simple Dynamic String (SDS) SDS是在redis中用于表示字符串的数据结构,相比C语言...

  • Go语言操作Redis

    Go语言操作Redis 在项目开发中redis的使用也比较频繁,本文介绍了Go语言中go-redis库的基本使用。...

  • Go语言数组和slice

    Golang的数组与切片 相同点:都属于集合类的类型,而且他们的值也都可以用来存储某一种类型的值 不同点:数组类型...

  • Go-数组与slice

    本文将讲解Go语言中的数组与slice。之前看到网上好多 《深入理解slice》、《深入解析slice》... 的...

  • 七、Go切片

    七、Go语言切片(Slice) Go 语言切片是对数组的抽象。 Go 数组的长度不可改变,在特定场景中这样的集合就...

  • golang数据类型

    Go语言中有四种复合数据类型:数组,slice,map,结构体 数组和结构体都是聚合类型,长度固定。而slice和...

网友评论

      本文标题:go语言的slice和redis的SDS对比

      本文链接:https://www.haomeiwen.com/subject/gtgywhtx.html