Are len(string) and len(slice)s O(1) Operations in Go?
Go programming language provides various data structures, including strings and slices. A common operation performed on these structures is determining their length using the len() function. The question arises whether this operation is an O(1) operation, meaning it takes constant time regardless of the input size.
Length of Strings
Strings in Go are immutable sequences of bytes. Internally, they are represented by a string header, which stores the length and a pointer to the underlying byte array. The len() function for strings simply returns the length field from the string header, which is an O(1) operation.
Length of Slices
Slices in Go are flexible views into an underlying array. They are characterized by three values: length, capacity, and a pointer to the underlying array. The len() function for slices returns the length field from the slice header, which is also an O(1) operation.
Conclusion
Both len(string) and len(slice) operations in Go are O(1). This is because the length information for strings and slices is readily available in their respective headers, allowing the function to retrieve it quickly without the need to iterate through the entire structure.
The above is the detailed content of Is `len(string)` and `len(slice)` O(1) in Go?. For more information, please follow other related articles on the PHP Chinese website!