4 ms·
Bounds checking can be a nuisance in Golang as well. One trick I've picked up is if I want to iterate over some small prefix of a slice, say the first 10 bytes
by honkhonkpants 10y ago
Bounds checking can be a nuisance in Golang as well. One trick I've picked up is if I want to iterate over some small prefix of a slice, say the first 10 bytes of a slice of bytes that is known to be longer than 10 bytes, it is tempting to do this:
for i := 0; i < 10; i++ {
something(honk[i])
}
But if you do that, you get a bounds check on every iteration. Much faster to do this:
subhonk := honk[:10]
for _, v := range subhonk {
something(v)
}
There's no range check inside the loop of a golang range iterator, for obvious reasons.
- dikaiosune 10y agoRust does this as well with iterators and iterator adapters -- I just forgot to include the version that did so in the blog post. Writing a loop like this: let mut count = 0; for b in &bwt[(i * self.k) + 1 .. r + 1] { if b == a { count += 1; } } Gave me similar performance to the filter/count iterators, as both elide bounds checking. I thought I mentioned that in the parting thoughts, but I may be misremembering and I have to run.
- pkaye 10y agoGood to know this. Some reason I felt in my mind that the first version would be faster because I am providing more information...