Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are assertions compiled out of production builds (other than performance)?

The typical argument for removing assertions from production code is performance. This doesn't make sense to me. Yes, stripping a few assertions out of the performance-critical 5% or so of your code can be a useful optimization. For the other 95%, though, they probably have no measurable effect, and asserts can only increase the likelihood that, if your code has a bug, it will fail fast and in an easy to diagnose way.

I do most of my programming in D, which has an enforce() function that does basically what assert() does except that it stays in release builds. I typically find myself using enforce() most of the time, and assert() only in a few places where enforce() would be too expensive.

Is there any other reason besides performance to remove asserts from release builds? If not, why don't languages make the default behavior of asserts to always execute even in release builds, and provide a second function that's more verbose and harder to remember, something like expensiveAssert() that is stripped out of release builds and recommend its use only in performance-critical parts of your code?

like image 876
dsimcha Avatar asked Feb 28 '23 16:02

dsimcha


1 Answers

I think assert() was meant as a pure developers tool in the first place.

A piece of software for end-users should provide some kind error handling (by logging and/or displaying a message to the user). assert() does not provide error handling.

However, I typically use my own release and debug assert functions. Both release and debug assert are only used for unusual errors - which should never occur. But they give a useful error message (useful for the developer, usually not so helpful for the end-user).

Errors that may occur (input/output, mis-configuration, ..) are explicitly handled and give a message to the user.

like image 103
Frunsi Avatar answered Mar 22 '23 23:03

Frunsi