[Idea] Faster derive(Hash) for types without padding

I think you posted the wrong link — that link is to bytemuck docs. In any case, I took a look at your currently posted benchmark code and, though I don't think this is the problem, I think you're using black_box wrong; you have

fn hash_it(value: impl Hash, mut hasher: impl Hasher) -> u64 {
    black_box(&value);
    black_box(&hasher);
    // actually hash the value
    value.hash(&mut hasher);
    let result = hasher.finish();
    // black-box the output for accurate measurement
    black_box(result);
    result
}

but what you should be doing is passing the values of interest through the black_box function, like this:

fn hash_it(value: impl Hash, mut hasher: impl Hasher) -> u64 {
    black_box(value).hash(&mut black_box(hasher));
    let result = hasher.finish();
    black_box(result)
}

It might be that this doesn’t matter in the current implementation, but doing it this way is important in principle to avoid the optimizer making use of knowledge about the value. It's also shorter!

2 Likes