Question: Are the len() calls on strings (string) and slices ([]int) constant-time (O(1)) operations?
Answer: Yes, the len() call is an O(1) operation for both strings and slices.
A string header contains a pointer to the backing array and its length. The len() function simply returns the length field from the string header, making it an O(1) operation.
Slices have length, capacity, and a pointer to the underlying array. Similar to strings, the len() function returns the length field stored in the slice header, giving it an O(1) time complexity.
Builtin.go Explanation:
The builtin.go file contains documentation for Go's predefined identifiers, such as len(). The excerpt you cited indicates that the items documented in this file are not part of the actual builtin package but exist solely to provide documentation for language-specific identifiers.
The above is the detailed content of Is Go\'s `len()` Function for Strings and Slices Constant Time (O(1))?. For more information, please follow other related articles on the PHP Chinese website!