user1424739
user1424739

Reputation: 13655

How fast is it to call len() on a slice?

I am wondering how fast is it to access len() of a slice. If I need to use the length of a slice for a few time, is it worthwhile to store it to an int variable? Or calling len() will be optimized as if an int variable is accessed? (In such case, there is no need to store the length of a variable by the user.) Thanks.

Upvotes: 2

Views: 776

Answers (2)

Laevus Dexter
Laevus Dexter

Reputation: 492

All of build-in functions not actually functions. It might be bunch of another functions or just one asm instruction (as for this case).

Here's slice struct:

type SliceHeader struct {
    Data uintptr // sizeof(uintptr) = 8 byte
    Len  int
    Cap  int
}

To get len of slice, we should to get offset from pointer of slice. Go-idiomatic variant looks like following:

*(*int)(unsafe.Pointer(uintptr(pointer_to_slice) + 8))

As you can see, output goasm code of len(b) equals one instruction: https://godbolt.org/z/z0PtMe

var b1 = []byte{1, 2, 3}
var b2 = []byte{4, 5, 6}

func main() {
   l1 := len(b1)

   if len(b2) == l1 {
       println(l1)
   } else {
       println(len(b2))
   }
}

l1 := len(b1)

=

movq "".b1+8(SB), AX // ax == l1

but, for len(b2) == l1 compiler creates additional variable:

movq "".b2+8(SB), CX // cx == len(b2) in "if" statement

So, we can conclude that creating new variable for length does not affect performance.

Upvotes: 2

Gavin Xu
Gavin Xu

Reputation: 78

Here is my understanding:

You can regard slice as a struct,of which length is a member.

The only thing function len() does is to read that member of type slice struct,thus there is no need to worry about its performance---it's as fast as reading the length int you create by yourself.

Upvotes: 2

Related Questions