padfoot
padfoot

Reputation: 851

Are len(string) and len(slice)s O(1) operation in Go?

var s string
var slice []int

len(s)
len(slice)

Is the len() call on strings and slices, O(1).

From this golang official blog, I can see that the slices have the length, capacity and pointer to the underlying array. So I understood, that the len() on it may be a O(1) operation. But what about strings? Is the length of strings also internally associated with the data so that len() just looks it up and returns it?

I looked at the source builtin.go but couldn't make anything out of it.

Upvotes: 7

Views: 3247

Answers (1)

Thundercat
Thundercat

Reputation: 120970

A string header contains a pointer to the backing array and a length.

The len() function returns the length field from string and slice headers. It's an O(1) operation.

Regarding builtin.go. The file says:

Package builtin provides documentation for Go's predeclared identifiers. The items documented here are not actually in package builtin but their descriptions here allow godoc to present documentation for the language's special identifiers.

Upvotes: 13

Related Questions