How fast is the cap() function in Golang?

Viewed 68

Golang has both len(array) and cap(array). The former returns the length of the array/slice (that being the amount of elements the array has); as I understand it, that function is O(1) However, I don't know the efficiency of the latter; is it O(1) as well?

2 Answers

For slices, both len and cap simply return the corresponding values from the slice header, so they are constant time operations.

For arrays, both len and cap are compile-time constants.

Internal definition of slice types like:

type _slice struct {
    // referencing underlying elements
    elements unsafe.Pointer
    // number of elements and capacity
    len, cap int
}

For slice, it is O(1) to get len or cap field.

len() and cap() of array are evaluated when the program compiling.

For array, it is O(1) to get len or cap field as well.

Related