Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
cmd/compile: range loops on slices of large types possibly surprisingly expensive #31588
What version of Go are you using (
@go101 please keep your comments constructive.
@seebs under the hood, the compiler makes a copy of the value so that subsequent code can safely modify that value without side-effects. I would expect that the extra copy would be optimized away in most cases. The exception would be cases in which we treat the value as opaque because it is large (struct with > 4 fields, array with > 1 field). If that is accurate, then this is probably effectively a duplicate of #24416.
Huh, I didn't even think to check it with small structs. So looking around, the original case involved a slice member, and experimenting on godbolt, it seems to me that a slice counts as multiple members for purposes of that optimization. A struct with four int64 members, only one of which is accessed, doesn't show the whole copy, but five do. But if I have a byte and two int64s, it copies. which I guess makes sense; a slice is three things.
And yes, i would want compilers to optimize the code, where possible. I value performance, and I value clarity, and I do not like having to choose between them.
I keep thinking about this and inventing range-by-reference, and thinking "gosh, i wish i had that". and then thinking "gosh, i sure hope no one else whose code i have to maintain ever gets that." And realistically, the worst other programmer whose code i've had to deal with has usually been "me a few months ago" so probably I don't actually want it.
To clarify: Yes, I think this is a duplicate of #24416. Thanks for spotting that.