200 points · by y4m4b4 · 9y ago · 136 comments
Please don't go around naming all your returns just because today's compiler happens to generate better code with them. This is a compiler issue that I'm confident will be fixed one day, especially if you do the right thing and file an issue.
But by all means, if you're profiling and your inner loops are actually slowed down by this, then make the change. And add a comment so that someone might be able to change it back some day when the compiler's improved.
We should just fix the compiler.
But it's been a process.
Go 1.5 was the first self-hosting release, with the Go compiler auto-translated from C to Go. But it was still fundamentally Ken's C compiler in Go syntax.
Every release since (Go 1.6, Go 1.7, Go 1.8, Go 1.9) has been cleaning it up and making it more Go like and less C like.
Meanwhile, the backend was also retrofitted. Go 1.7 included an SSA backend for amd64 (https://golang.org/doc/go1.7#compiler).
Go 1.8 included it for all architectures and added more SSA goodness.
Go 1.9 adds yet more, but some things are still not pushed down into SSA as well as they could be. (e.g. https://github.com/golang/go/issues/5147#issuecomment-247685...)
Nowadays we can add optimizations much more easily, including writing matching rules like in https://github.com/golang/go/blob/master/src/cmd/compile/int...
Meanwhile the whole toolchain keeps getting cleaned up and more hackable.
In Go 1.9, the compiler is now parallelized, which would've been impossible earlier. (https://tip.golang.org/doc/go1.9#parallel-compile)
So, it keeps improving. Just remember the Hello World compiler we started with.
Also amusing in retrospect is that when Go first came out, despite having a very basic compiler at the time, people coming from scripting languages thought we were so fast.
Ignoring the style issues for a second (I'll pick that up later), if I'm looking at some code and there are two equally viable alternative ways of writing it, one of which saves a chunk of memory* or is faster then it's just perverse to choose the path of larger/slower code. I do this with regular expressions/string functions. I see people use regexes a lot, but the tool I reach for first when doing string operations are the built-in string functions, eg. https://golang.org/pkg/strings/#Contains or https://ruby-doc.org/core-2.4.0/String.html#method-i-start_w.... I'm not optimising, I'm just not de-optimising.
Back to the style issue, at this point if you really feel strongly about the way it looks in the editor, or in documentation then I can see why you would choose one method over the other, choosing the less desirable, but theoretically faster code would absolutely be a case of premature optimisation. I personally don't have a particular preference either way however, and feel like the reasons outlined in the style guide are rather fragile. So ultimately, if I pick up some code full of named return values I don't think it would bother me, in the same way that code that uses none, or mixes them where someone thought it appropriate doesn't bother me either.
* There may be benefits other than just disk/distribution size. Many years ago I read about the benefits of small binaries, something relating to CPU caches, though that may be out of date now and I forget the details.
In contrast, the case in this article seems like table stakes for an optimizing compiler. It's just not eliminating common subexpressions. There's no reason to contort your code around something that should automatically happen.
start_with: 5703143.1 i/s regex: 2821224.4 i/s - 2.02x slower
That aside:
> There's no reason to contort your code around something that should automatically happen.
Absolutely, but it's a question of style at that point. "Contorting your code" suggests using a less desirable style/syntax for some gain, and I'd agree would be premature optimisation. If you're just making a choice between two styles that you consider to be pretty much equal then it's just pragmatic.
edit: Forgot to add, yes, I agree that this should happen automatically in the compiler :)
Having said that, this is certainly something that should be fixed in the compiler.
On a related note, in the final assembly, the compiler could also have optimized the 4 RETs into 1, then optimized away all of the conditionals, turning the sample code into the equivilent of "return objectInfo()"). Of course, in a real example, these optimizations would not be possible; but they do show that these reduced cases are not the best way of benchmarking performance.
In the first way, each branch allocates its own objectInfo struct. In the second way, all the branch exits share the same single objectInfo struct which I assume is implicitly initialized to the zero value by the compiler.
Functionally these are the same, but couldn't you achieve the same results without named return values by just allocating a single objectInfo at the top of the function and returning it?
Why not just declare a record in scope and return that? Why rely on a sneaky little piece of syntax tucked away in the return value? Aren't gophers supposed to be all about a regular language with few surprises?
It's not a sneaky piece of syntax, in fact it is required to use that syntax if you want to reference or modify the return value of a function in a deferred function call.
I don't like the syntax and hate that Go forces you to use it in the above case, but it's definitely not sneaky syntax. Any regular Go developer should be expected to know about this construct.
I've hated this feature since I learned about it. Its existence is one of the many reasons I dismiss arguments about Go being easy to read.
In fact named returns appear all over the Go source code itself[0] and the Effective Go section on named returns[1] seems positive about their usage.
[0] https://github.com/golang/go/blob/master/src/os/file.go (file taken at random)
[1] https://golang.org/doc/effective_go.html#named-results
Personally I use named returns heavily because it helps document what each return is used for. Which is particularly useful in IDEs like IntelliJ where you get the tooltip popup with the function parameters and returns. But frankly I find named returns just as useful when reading back old code on GitHub or even just in vi.
I also notice I'm not the only one who uses them in production code. Here are some popular packages by other talented Go developers (all .go files picked at random)[2][3]:
[2] https://github.com/kr/pty/blob/master/util.go (this package creates UNIX PTY files)
[3] https://github.com/chzyer/readline/blob/master/operation.go (readline package used by cockroachdb and Netflix)
In fact of the packages I checked, I could only find one package that didn't make heavy use of named returns[4]
[4] https://github.com/go-sql-driver/mysql/
So if they are frowned upon, I'd be interested to know more about who and why.
/r/golang consensus is against using named values. I disagree with it, but the consensus is there. Or at least I think that at the very least named return values should indicate that someone is doing something with a defer.
As for why, I don't get a clear sense. I hate to characterize an argument I disagree with, but I have to admit I just sort of get the sense that it was one of those things that just sorta happened. Sometimes one person says something, another person half-heartedly agrees, and before you know it it's getting parroted around by an entire community. I acknowledge again that as I don't agree with it this may be a rather harsh read on my part.
Personally the only time I find them to be acceptable is when you have to reference a returned value in a defer. All other usages are questionable, though this is a taste thing and is likely because of my dislike in it's usage as a way of omitting a `var` in a function body (and also the fact that naked returns are magical in comparison).
[1]: https://github.com/golang/go/wiki/CodeReviewComments#named-r...
The rationale was that they can make code hard to follow, especially when one of the returns is err and you have other errs in your function.
Lastly, to be clear, I didn't mean to imply they were frowned upon in all cases; only that you should prefer normal returns unless you have a compelling reason.
In my mind there are only two reasons to use named returns. The first is when writing interfaces, and you want to document the returned values in a nicer way (in addition to the godoc). This is mostly a taste thing and is not required.
However, the second one is required by the language and that is deferred function calls that interact with the return value of a function. If you want to have a deferred function call that does some cleanup but has to check the error value of the function (for example a cleanup that only runs if an error occurred) then you have to use named return values. If you want to have a deferred function that changes the return value of the main function then you also need named return values. This is a fairly annoying requirement of Go, but I understand why they felt it was necessary to do things that way to make it feel more explicit.
Other than that, in general named returns make functions harder to read (in my opinion). In a similar vein, I really don't like Ruby's or Rust's implicit returns (though at least Rust is less magical about it).
In my perfect world, we would have named return values by default, so then we could use them to document the return values, but never empty returns. Empty returns are the only problem with named return values Imo, as it's easy to accidentally slip values into the return that you didn't intend.
Though, I had always wondered about returning copies like Foo{} on every return.. guess I know now.
edit: As an aside, I should not dismiss your cluttering comment. I did so, because I feel it's unrelated to this exact topic. If named return values, something which by it's very nature conveys additional information, is cluttering the godocs, then that should be a bug, and filed/fixed accordingly. Imo.
The name doesn't even appear in the function. A name that is declared but not subsequently mentioned serves no purpose (or some side purpose/hack).
In the "NoNamedReturnValue" variant, the return type is still declared. The compiler could, from that type alone, infer that "return" means "return a representative default instance of that type".
That is to say, why can't Go programmers just have this:
// oi name removed:
func NamedReturnParams(i int) (/* oi */ objectInfo) {
if i == 1 {
// Do one thing
return // wee, allow this anyway!
}
if i == 2 {
// Do another thing
return
}
if i == 3 {
// Do one more thing still
return
}
// Normal return
return
}
Also, why can't the compiler just optimize away the "return Objectinfo {}" statements down to "return", if those really are equivalent. return { named_var_1, named_var_2 }
const { named_var_1, named_var_2 } = f()
But then I read the article.I don't know really what is going on in this article on a quick reading, but it builds by existing sense that go is a really cool language that I ought to get into.
I have no idea if anyone wants to help me understand, but in the last part where he changes to use a named return parameter, he says, you may also "enjoy the cleaner look of the source code, too". To me the only difference I see is the return name, to the right of the existing function signature. What was I missing that makes this actually cleaner?
Returning a new unnamed variable for every return will cause all of the unnamed variables to be allocated.
It's interesting, I don't use this feature of the language... my default way to write this would have been:
func NoNamedReturnParams(i int) (*objectInfo) {
obj := &objectInfo{}
if i == 1 {
// Do one thing
return obj
}
if i == 2 {
// Do another thing
return obj
}
if i == 3 {
// Do one more thing still
return obj
}
// Normal return
return obj
}It really hammers home the concept that a function is a transformation, and of what into what. And I think this syntax would probably encourage pure functions. And it's so useful to allocate the return in the top line. I really like go.
Named returns are a Go thing mainly because of defer.
e.g. https://play.golang.org/p/gdac5QR-wW
This can also be used to return the default value for a type by never assigning anything to the return value.
https://play.golang.org/p/7bfiSqKY_w
I was also looking for a "spread" / ... operator, but couldn't see a way to do that.
I went into reading this expecting that use case but was saddened it was not mentioned. The use case the author does give is kind of meh, I find it to be harder to understand what is going on than returning as usual, and that's worse than the slight supposed compiler gain is worth.
It's much easier to read code where there is a clean "return nil, fmt.Errorf(...)".
Named return values are one way to declare your return value up front but you could just as easily have had a oi := objectInfo{} line at the top of your function too with the same effect.
Fortran functions have always (since Fortran II anyway) used named result values; so did Pascal. Since you can now pick the name of the result value variable in Fortran, I find it a useful convention to just always put RESULT(RESULT) on my functions.
It makes the code a lot harder to read, and you need to keep more memorized "magic" in your head. For example, you can't just look at the return values to figure out what a function returns, now you need to look to see if the return values are named, and then trace through that.
I very much prefer explicit code as opposed to implicit code, especially on a day-to-day basis. It just makes my life a lot easier in the long run.
You can use non-bare returns with named return values, just mention the names in the return statement. This compiles to the same code as the bare return.
I'm a bit ambivalent about bare returns, but named return values are useful, especially in the presence of defer statements.
I think they are pretty explicit and simpler, because there are defined in a single point of our code. Anyway, we probably have different backgrounds :)
Although it wasn't your point, what I don't like is mixing bare and named return. I think it's better to stick to one style or the other.
What am I missing?
If they are never mentioned in the body you probably have a return of the default nil value for the named return variables.
But then at least one return is not naked and returns some value, discarding the named one.
I think it's a bad use of named returns.
The named return value is default-initialised (zero-initialised) before the function body (you don't have to assign to it, you can just modify it in place), and if you don't explicitly return a different value it will be returned regardless of you using it or not.
go fix?
Also, it seems like this is begging for a compiler optimization that will make this all obsolete...