183 points · by ingve · 2y ago · 158 comments
Basically: the critical functions in the benchmark are small enough they were being inlined by the compiler, which means it's possible for the compiler to further optimize the loop to avoid all comparisons in some cases, producing an inaccurate result for some of the benchmarks. You can fix this by adding noinline directives to the methods.
I'll be publishing an update to the article and a post-mortem on how this slipped past review. The rank ordering of techniques in the article is unchanged, but the magnitude of the difference is not nearly so large.
But even if those numbers had been accurate, it is important to think about how they compare to the operations being performed. Taking 4 nanoseconds to check for an error sentinel is not a huge deal when you've spent microseconds or even milliseconds waiting for a network service.
These are all fair tradeoffs for the simplicity and ergonomics of Go's error handling. They rarely matter for performance because the happy critical path of most programs does not produce lots of errors. These are just nuances worth recognizing in a thread specifically about the isolated overheads of errors.
It should (hopefully!) be self-evident that "hot loops" in which single-digit nanosecond performance differences are meaningful, are (a) exceptional; and, more importantly, (b) not a place where you'd make any kind of function call in the first place!
Particularly in JITed languages, if the multiplier is hyperbole today, there may be a day in the future where it’s accurate.
Funny I was just reading this the other day : https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotn...
It's probably not the first thing you spend effort on when optimizing but it gets better over time.
A well-designed error handling system can feasibly reach this goal, at which point no more optimization is possible.
Edit @hinkley: I am unfortunately in hacker jail, and have used up my post quota, so I have to edit my post rather than reply to yours. Reply follows.
Throwing, the way Java and C++ do it, exceeds the minimum cost of an error, yes. Not that this is some sort of show-stopping problem, I'm discussing the minimum cost, not what level of cost makes errors too expensive.
A branch-not-taken, which is the opposite of processing an error, caught or otherwise, is what I described as practically free. Not always. If the only path forward is, for instance, to reference a pointer, and the error would mean that the pointer is a null pointer, the chip would have to wait for the branch to coalesce, which might mean a minor pipeline stall.
But if the processor can do further work, such as checking for an error on malformed input, where it's legal to speculatively execute the next decode on the predicted branch, it really is practically free. It costs considerably less than one instruction. If the branch triggers, the processor spills all the speculative work and switches. Since errors are expected less frequently than success, more or less by definition, that's the correct tradeoff.
This is why I described the error branch as "cold". The processor should predict and speculate on the happy path.
Zig is an example of a language where errors can be as inexpensive as a superscalar check on a given register while the main path moves forward. This is also possible in C when checking errno(). I can't speak for Rust, but enormous amounts of work have gone into that compiler, and it should indeed be possible to compile a match-on-Result to the same efficient level. Perhaps trickier since Rust doesn't "know" what an error is, but I suspect that in practice it can get this right.
Not that it's even mostly up to the compiler: there are ASM hints for the branch predictor in some instruction sets, but modern branch predictors don't need those to handle the case where 99+% of the time execution proceeds on one branch. It's conventional for compilers to emit "branch on cold, proceed on hot", but it's been a long time since that has mattered for execution speed. You'll get a bit tighter on a chip with no predictor and a shallow pipeline, like AVR, but for anything which can run an operating system it's almost irrelevant now.
I see no a priori reason why Go shouldn't achieve the minimum level either. Languages which use exceptions and try/catch must do some bookkeeping, which imposes a cost on the code whether an exception is raised, or not. That can be minimized, but not to the limit I'm talking about.
You might find this link interesting: https://ziglang.org/documentation/0.12.0/#Implementation-Det...
Note that the costs described are for the ability to generate an error trace, not error handling itself. This cost is only paid in debug and ReleaseSafe modes.
func BenchmarkFoundErrorsIs(b *testing.B) {
var es errStore
for i := 0; i < b.N; i++ {
val, err := es.GetValue(true)
if err != nil {
if errors.Is(err, notFoundErr) {
b.Fatal("expected found")
} else {
b.Fatal(err)
}
}
if val == nil {
b.Fatal("expected not nil")
}
}
}In practice, if you are really writing performance critical code, you kind of just need to benchmark and determine which bottlenecks are holding you back. Knowing the performance hit of some patterns is still useful, but it's not a substitute for actually measuring the performance.
That said, the even better solution would probably be if future Go versions could just make the idiomatic code faster somehow, so that it is less likely to be a bottleneck. But, this is the case for many patterns in Go, as Go and its stdlib doesn't really prioritize performance or zero (runtime) cost abstractions. (They justify this with data; in developers surveys, time and time again Go developers greatly express their priority in having robust, "safer" code over higher performance code.)
An error should by default be considered non-recoverable, to be returned when something goes very wrong. Semantically, a table not existing isn't really an error, it's something you expect to happen all the time.
remains a bad idea.Seems like the reason for this article is the reaction to that one: https://www.dolthub.com/blog/2024-05-10-ok-considered-harmfu...
The last section of the blog has a discussion of aesthetic and philosophical concerns around using errors for control flow. I'm against it, for the reasons I provide. YMMV.
The real takeaway should be that one must always be careful with shadow variables and generally use them as immediately as possible.
Asking to retrieve a table that doesn't exist is an error, because the answer is that there is no table; the operation was unsuccessful. There failed to be retrieved any table, but as the table always could have either existed or not, this is not an exceptional case. Nothing went wrong: you simply asked to retrieve a table and no table was found, so you get that back as an error.
However, trying to perform a table operation on that unsuccessful result generates an exception, because you violated a contract: you can't operate on something that doesn't exist. Sure, you can operate on the representation of nonexistence (that is, null), but you attempted to operate on a table and you don't have one.
The computation stops prematurely with an exception because the operation expects the table to necessarily exist. There is no unsuccessful result to be returned because the operation didn't even make it to the point of failing; the performance itself of the operation failed. The operation is entirely invalid and returning any result would be incorrect.
At least, that is my personal understanding of the terms.
For example, most things in Rust are errors and not exceptions, because exceptions (panics) generally terminate the thread, or abort the process, depending on user preference or runtime environment. Anything that isn't fatally unrecoverable deserves to be an error - in other words, a `Result::Err` - which can be handled by the caller, as opposed to panics, which are not guaranteed to be catchable (unwinding is not a required part of the language, it is an optional convenience).
Most failures in JavaScript are exceptions, because you are not made to check anything, and everything is dynamically typed, so if you make an assumption that isn't true, an exception has to be raised to stop you. Luckily, there is try/catch. It can also be difficult to represent errors without exceptions, you instead have things called "error states" which are basically certain non-errors being treated as errors by user code, when either that result is undesired even if perfectly normal, or that result is the only/easiest way for the error to be reported by the source.
Anyway, my point is that the article probably means to use the term exception and say that a boolean is better than an exception when the error isn't an exceptional case. And in that case I would agree. In Rust, I don't want my program to crash when I ask for a nonexistent table - I only want that to happen later if I decide that the table's nonexistence is a fatal error in the context of the whole thread.
In Java, C#, C++, for example, exceptions are meant for any situation where the operation you asked for can't be completed successfully, for whatever reason. The most common example is IOException: if you asked to read 200 bytes from a socket, but the connection got interrupted after 100 bytes, that's an IOException. This would not be appropriate as a panic in Go or Rust, for a comparison of the difference in philosophy.
That is indeed an example I included, yes
> In Java, C#, C++, for example, exceptions are meant for any situation where the operation you asked for can't be completed successfully, for whatever reason. The most common example is IOException: if you asked to read 200 bytes from a socket, but the connection got interrupted after 100 bytes, that's an IOException.
- Java has checked exceptions, which... ugh, I'm not going to get too much into this, but this is basically their terrible way of representing expected errors while reusing the try/catch syntax. Yes, the thing is called exceptions at the language level. Yes, they do interrupt control flow. But fundamentally I consider them mere errors.
- C++ overuses exceptions in a similar way, except they're not checked because fuck you, nothing in C++ is checked.
The relevant quote's talking about semantics, so I'm talking about errors and exceptions as something that transcends the individual programming language. Different languages are different and don't always (even usually don't) map these concepts 1:1.
Your understanding otherwise seems on point, but I'm not sure they can ever be the same. An exception is the representation of programmer fault. An error, on the other hand, is the representation of faults outside of the programmer's control.
Like you point out, operating on a missing table is a mistake made by the programmer. This fault could have been avoided when the code was written. The table not being there is not within the control of the developer (with some assumptions of what table is meant to mean here) and no amount of perfect coding could have avoided the situation.
> Most failures in JavaScript are exceptions
Idiomatic Javascript suggests handling errors using its exception handling mechanism, but the payload is still error in nature. In fact, the base object the idioms suggest you use to hold error data, passed using the exception handler, is literally called Error.
Javascript may be confused by having no official "Exception" type. Although arguably it does not need one as you can simply throw a string, which is all you need for an exception. The exception handler will tack on the rest of the information you need to know automatically. Java takes a different opinion, though, having two different, albeit poorly named, built-in classes for errors (Exception) and exceptions (RuntimeException).
The go standard library uses sentinel errors. ErrNotFound is actually good to use, because otherwise, a `Get` call can end up returning `nil, nil` (*Value, error). Which is just bad.
[0]: https://github.com/golang/go/blob/9b43bfbc51c469ec13fca24960...
if err == nil || target == nil {
return err == target
}
So the overhead is the function call and 2 comparisons. I wonder if the `isComparable := reflectlite.TypeOf(target).Comparable()` line was moved into a separate function if the compiler would inline Is() reducing the perf impact.Possibly related: https://github.com/golang/go/issues/61502
Looks like they're working on improving the inliner.
https://github.com/golang/go/commit/af43932c20d5b59cdffca454...
I'd be interesting to see the benchmark after that.
I expect the vast majority of code spends so little time in errors.Is() that trying to optimize it saves nothing. Profile first, and change it later if needed; as Go is statically typed such a change is trivial.
Am I missing something, or could this be partially mitigated by adding a check for `err == nil && target != nil` and vice versa, rather than `err == target`?
https://github.com/golang/go/blob/9b43bfbc51c469ec13fca24960...
if err == nil || target == nil {
return err == target
}
are a "pretty big performance penalty", there isn't much work going on. I mean, of course, these 2 or 3 comparisons + the function call of `Is` are at least double that of err != nil
even if `Is` would have been inlined by the compiler.https://github.com/golang/go/blame/adbfb672ba485630d75f8b559...
The latest available release only checks if target is nil.
So, no, errors aren't special and should obey semver but you deliberately can (and should) signal that your users can't exhaustively match a thing you know will change.
For this reason I personally don't like `#[non_exhaustive]`. I don't expect my code to keep compiling when I upgrade the minor version of my dependencies, and as long as the reason is simple, like a new enum variant was added, then I'm happy that it errored and will happily fix it.
This perfectionist attitude towards semver is why so many projects get stuck forever at v0. https://0ver.org/
However it's also only fair to note that the Rust ecosystem does not consider every [potential] breaking change a major one. https://predr.ag/blog/some-rust-breaking-changes-do-not-requ...
Does that not exist in Rust?
(although you do absolutely have to be careful about what you are returning in a client-facing error message etc. don't return the parts of the stack trace that leak information about your application to an actual client, they should be caught by your framework and turned into generic "4xx git rekt"/"5xx we made a fucky wucky" messages that don't reveal too much about your environment.)
not a java problem specifically for either of those, it just seems odd coming from that world that there's not a concept of a "recursive exception stack" like that in rust?
while I agree to some degree, but when performance comes into picture, what really matters more is normal path vs surprise path rather than happy path vs error path
it's hard to argue what is a happy path in the code, but it's not wrong to say that io.EOF check is a normal path of the code i.e. not a surprise in production. the bad performance of errors.Is is something to be improved upon but it's not a surprise in production when there are a large number of `errors.Is` checks during normal path of the code
now coming to the surprise path of the code, here's where performance gets really important, no one wants their code to suddenly hog 100% CPU because of some special error case - https://blog.cloudflare.com/cloudflare-outage . but such surprise paths often contain a large amount of business logic that weigh much more than how slow errors.Is function is compared to a boolean check
it would be interesting to see where this line of reasoning is valid but IMO performance isn't a good argument against why errors are not normal outcomes of operations in production
but thumbs up for the article, now I know what to reference for backing the below pattern that I often use, when I first saw the errors.Is it was pretty obvious that its going to be slow but just didn't have time to prove it and use below pattern
```
if err != nil && errors.Is(err, x) {
} else if err != nil && errors.Is(err, y) {
} else if err != nil {
// handling unknown error
}```
I learn something about a tool I love and have used for 10 years and it isn't snarky, flamebait nor preachy.
if err == nil || target == nil {
return err == target
}
[0]: https://github.com/golang/go/blob/9b43bfbc51c469ec13fca24960... if target == nil {
return err == target
}
[0]: https://github.com/golang/go/blob/go1.22.3/src/errors/wrap.g...I have to say that nearly all the production code I write in Go is typically stuff interacting with external services like databases and SaaS APIs, so the difference in nanoseconds here is not going to move me away from using the safe idiomatic approach, but it is something to bear in mind for whenever I might use Go for very computationally intense tasks.
It's a shame that errors.Is is slow for general use, and at least some of that seems attributable to the Comparable change requiring reflection. Multi-errors seems to have bloated the switch. And of course the lack of a happy-path that was fixed in [1].
Since Go already has two ways of handling exceptional state: return or panic, it does feel like a stretch to also introduce a "not found" path too. All bets are off in tight inner loops, but I think as a general coding practice, it'll make the language (de facto) more complicated/ambiguous.
But my take away is that the question has been kicked off: can wrapped errors be made more efficient?
1. https://github.com/golang/go/commit/af43932c20d5b59cdffca454...
The Venn diagrams of "situations where single-digit nanosecond performance differences are important" and "situations where one would use errors.Is" have no overlap.
Tempest in a teapot.
Nobody's real-world code is being slowed down by 500% because all real world code is doing much more than just checking errors. All I see from these results is a 15-16ns cost to using errors.Is versus an additional boolean.
Even the examples ("GetValue") hint at an extremely common use case: reads from a data store. A case where single-digit milliseconds is considered "all good performance-wise" for the most common SQL databases, clocking in at 100000x the time scale of errors.Is.
This reminds me of "latency numbers every programmer should know". Work with the standard library and other well-conceived go projects and you gain the intuition that error handling and bit-twiddling arithmetic don't belong together. That's the real story here, and OP's article is way wide of the mark.
Is this really a common recommendation in the Go community? Seems like returning `bool` to indicate if the value was found is somewhat of a no-brainer, since it follows the familiar approach used for map lookups and type assertions.
If this is s big deal perhaps you should be choosing a different language :)
Also BTW the nested `errors.Is` bench is wrong. Each function is wrapping the errors instead of constructing them preemptively and this is benching the time to create nested errors. Don't do this, in the test or real code. It makes it tough to read as a client.
Just a guess, I'm not a Go person.
If there's no attempt to recover in the code, then panic() wouldn't need to save any state and the compiler might just optimise out anything needed for recover()y.
I'd like to play with it a bit, to compare patterns I've done before and am too lazy to copy+paste ;)
Comparable code (for errors.Is()) written in C# takes about 4ns on M1 Pro:
(made unidiomatic and abstracion-heavy-ish for demonstration purposes)
https://gist.github.com/neon-sunset/65a8deeaac745ba159f990c7...
Of course were it rewritten to a TryGet or (object, bool), it would bring that to 1-3 CPU cycles, as everything would get inlined and lowered to a few branches.
(this does not make the point any less valid as the solution this is applied to discussed in the blog post uses "vanilla" runtime flavour)
If 19ns is critical to my existence, I'm certainly not going to spend hours of it finding out if a handful of ns might be shaved off by using another implementation.
> which is inadequate at systems programming
Implying that Go is a scripting language?
What motivates the “happy path only” programmer?
But for both contexts and errors: imo the tradeoff is overwhelmingly in favor of wrapping more, not less, in the vast majority of code. Context is useful and standard for many things, and wrapped errors carry a lot more useful information, and both of those are absolutely crucial for healthy interop with other code. Performance sensitive stuff can do whatever it needs, these are obviously terrible choices there so just don't even consider it.
* but not always! and it may change with time. Still, my contexts are regularly 10+ layers deep while my errors are rarely more than one or two.
Some background for anyone not familiar with Go errors:
A Go error is an interface value with an Error method that returns the error's text. A simple error can be constructed with the errors.New function:
var ErrNotFound = errors.New("not found")
A nil error indicates success, and a non-nil error indicates some other condition. This is the infamous "if err != nil {}" check. Comparing an error to nil is pretty fast, since it's just a single pointer comparison. On my laptop, it's about 0.5ns. Comparing a bool is about 0.3ns, so "err != nil" is quite a bit slower than "!found", but it's really unlikely the 0.2ns is going to be relevant outside of extremely hot loops.We can also compare an error to some value: "if err == ErrNotFound {}". In this case, we say that ErrNotFound is a "sentinel" (some error value that you compare against). This is about 2.3ns on my laptop; there are two pointer comparisons in this case and a bit more overhead in comparing interface values. (You can actually make this check almost arbitrarily expensive; you could have an error value that's a gigabyte-large array, for example.)
It's common to annotate an error, adding some more useful information to it. For example, we might want our "not found" error to say what was not found:
return fmt.Errorf("%q: not found", name) // "foo": not found
This is quite a bit more expensive than "return ErrNotFound". The fmt.Errorf function will parse a format string, produce the error text, and make two allocations (one for the error string, one for a small struct that holds it). This is about 84ns on my laptop--168 times slower than the fast path! But 84ns is still pretty fast, and you can't get away from the need for at least one allocation if you want to return an error that's varies based on the inputs of the function that produced it. (You can get faster than fmt.Errorf if it matters, but this comment is already getting large.)A problem with using fmt.Errorf in this way is that you can't test the error against a sentinel any more. This was addressed a while back in Go 1.13 with the addition of error wrapping. You can return an error that wraps the sentinel (note the %w format verb):
return fmt.Errorf("%q: %w", name, ErrNotFound) // "foo": not found
And you can then use the errors.Is function to ask whether an error is equal to ErrNotFound, or if it wraps ErrNotFound: if errors.Is(err, ErrNotFound) { ... }
On my laptop, producing a wrapping error like this and testing it with "err != nil" is about 91ns, and testing it with "errors.Is(err, ErrNotFound)" is about 98ns. So using Is is adding 7ns of overhead, which is not nothing, but is also pretty much lost in the noise compared to creating the error in the first place.The example in this blog post went a step further, though, and created an error with not just a single layer of wrapping but one with four. The error text in the wrapped error cases is:
GetValue couldn't get a value: queryValueStore couldn't get a value: queryDisk couldn't get a value: not found
(That is, by the way, a very difficult error to read. Don't hand users errors that look like that.)Creating a stack of four wrapped errors like this on my laptop is 396ns, and inspecting it with errors.Is is another 21ns. 21ns is waaaaay more than the 0.5ns for a simple "err != nil" check, but again the runtime here is massively dominated by the expense of creating the error--which in this case involves repeatedly creating formatted strings and throwing them away, and two allocations for each layer in the stack.
In general, when doing low level optimization of Go code, avoiding allocations is the biggest bang for your buck. If microseconds matter, you absolutely should pay attention to the cost of constructing error values. But the cost of inspecting those values doesn't usually become an issue unless nanoseconds count, and will generally be dominated by the cost of construction.
Also, even the slowest cases here are running about 0.5-1.5μs, which absolutely matters in some cases, but is irrelevant in many others.
I have found this to be the truth. I'm making a game in Go, and have learned that a smooth framerate depends on programming with allocation awareness. Always know where and when your memory is coming from.
We have in the past eliminated sentinel errors and gotten measurable gains from doing so, but this is mostly because our errors were both common (occurring several times on every request) and expensive to construct. The direct cost of errors.Is() was minor compared to the cost of building the error itself.
And you might be surprised how common it is for people to insist on wrapping an error at every layer of the stack. I've gotten in arguments with these people online, they're out there.
I want organizational velocity in the general case. If wrapping an error is in a hot path and shows up in metrics, yeah, remove the wrapping. Otherwise, wrap the error.
What is your argument against that? It would seem you find the compute savings of non-wrapped errors outweighs developer time and customer impact. If that is not what you are saying, please correct me.
My creds are using Go since 1.2 and writing massively scaled systems processing multibillion events daily for hundreds of thousands of users with 4 to 5 9s of uptime across dozens of services maintained by hundreds of developers earning the company hundreds of millions of dollars.
1. I think that it is preferable to handle the error where it happened instead of at the top of the stack. For a backend service, there's really only three things you want to do with an error: log it, maybe bump some metrics, and return an error code and ID to the client. You have a lot more information available (including a stack trace if desired) if you handle it at this point.
2. By wrapping the error up the call stack, you're building an ad hoc stack trace. Performance wise, this is (probably, haven't measured) a lot better than an actual stack trace, but as you said yourself, the top concern is debug-ability and developer velocity.
3. Wrapping an error doesn't provide just a stack though, you can add values to the error! Except...what does that really buy you vs. just adding the values to your structured logging system going down the stack vs. doing it on the way back up in an ad-hoc way? Those wrapped error values are a lot more difficult to work with in Grafana vs. searching based on fields.
4. If I have a stack trace, structured log fields, and a correlation ID, I personally don't get any value out of messages like ("could not open file), as I can just use the stack trace to go look at exactly what the line of code is doing. You could argue that with good enough wrapping, looking at the code wouldn't even be necessary, but I think that's pretty rare in practice. It also seems like a lot of extra work to spend a minute loading up the code in an IDE.
5. As mentioned in 1), what the client gets is just an error code and trace ID anyways. In fact, we actively don't want the wrapped context to be sent back to the client since it can be a security concern. If that's the case, we need to remove it and log it anyways. Why not just log the information in the first place?
Anyways, curious to hear your thoughts. I used to advocate for wrapping errors, FWIW.
I agree with your point about debugging, but I have a different idea how to best achieve it. Rather than wrapping an error at every stack layer, just take a stack trace when the error is created. This works great as long as... you don't design the system to require sentinel errors. Treating errors as rare, exceptional events rather than normal values used for control flow changes how you approach them.
This is how we use most errors in our code base. But we tend to not treat them as sentinels, we are only interested in the descriptive error messages.
Everyone understands that if A is 2x faster than B, then B is 2x slower than A. If you say either of these things to someone with a basic grasp of sums, and then tell them A takes one second, they'll know that B takes two seconds. It doesn't matter which one you supply. No one would get this wrong.