-4

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); which makes it immediate

cap(array) returns the capacity of the underlying array. However, is that operation O(1)? One would think that the capacity of an array is a value that the array has, and thus could see in O(1) time, but I can't tell for certain

Peter Petigru
  • 207
  • 2
  • 9
  • 4
    They are both constant time operations. The slice header has len/cap, and those functions simply return those values. len(array) and cap(array) are evaluated at compile time. – Burak Serdar Sep 15 '22 at 02:02
  • That makes a lot of sense, do you mind writing it as an answer? – Peter Petigru Sep 15 '22 at 02:23

2 Answers2

6

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.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
3

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.

spike014
  • 459
  • 3
  • 8