Thanks for making this library, BurntSushi.<p><pre><code> impl Decimal {
...
/// Returns the ASCII representation of this decimal as a string slice.
pub(crate) fn as_str(&self) -> &str {
// SAFETY: This is safe because all bytes written to `self.buf` are
// guaranteed to be ASCII (including in its initial state), and thus,
// any subsequence is guaranteed to be valid UTF-8.
unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
}
}
</code></pre>
<a href="https://github.com/BurntSushi/jiff/blob/08dfdde204c739e38147faf70b648e2d417d1c2e/src/fmt/util.rs#L186">https://github.com/BurntSushi/jiff/blob/08dfdde204c739e38147...</a><p>How much performance does `from_utf8_unchecked` buy us over `from_utf8`? It's saving iterating over a 20-byte array. Because the array fits in a single cache line, the iteration will run at the CPU's internal clock rate. I expect that a benchmark would not be able to detect the CPU time saved. Even a program that was only serializing these Decimal types at GB/s, the difference would be barely measurable.<p>As software engineers, about 80% of our time is spent coding. And about 80% of coding time is spent learning how the thing works. If we prioritize code clarity, we speed up 64% of our future work.<p>Performance optimizations always make code less clear. Using `from_utf8_unchecked` is a performance optimization. It makes the code less clear so it needs a three-line comment.<p>Engineering is all about trade-offs. Performance optimizations can be worth their clarity cost when they bring tangible benefits. Therefore, we need to measure. The comment doesn't say "Using `from_utf8_unchecked` because it takes 1ns while `from_utf8` takes 5ns." To make sure we're making a good tradeoff between clarity and performance, we need to measure the impact of the optimization and document it in the code.<p>Using `unsafe` also has a cost. Safety depends on invariants. Future changes to the code can break these invariants. The compiler is the most reliable method for detecting invariant-breakage. Let's take advantage of it. This means using `unsafe` only when its use brings tangible benefits that outweigh the risks.<p>I started my professional life as a Windows sysadmin. Dealing with worms and viruses was a large and unpleasant part of my job. During university, I learned about formal verification of software. It has great potential for making our software secure. Unfortunately, the tools are very hard to use. To verify a program, one must translate it into the language of the verification tool. This is a lot of effort so few projects do it. Now with Rust, we get verification FOR FREE! It's amazing!!!! So let's use it and move our industry forward. Let's make worms, viruses, ransomware, and data theft, into things from the barbaric early days.