RustCrypto / hashes

Collection of cryptographic hash functions written in pure Rust
1.81k stars 245 forks source link

comparing after dereferencing or unsafely indexing, which is faster? #476

Closed oilel closed 1 year ago

oilel commented 1 year ago
use sha2::*;
fn main() {
    let a = [0u8; 32];
    let h = Sha256::new_with_prefix(&a).finalize();
    assert!(a == *h);
    for (i, v) in a.iter().enumerate(){
        unsafe{assert!(*v == *h.get_unchecked(i))}
    }
}

Note: This code will panic, but don't care about that, I'm asking about the performance of comparing. The 1st implementation is using Deref operator, the 2nd is using unsafe indexing (.get_unchecked), which is faster when assert!?

newpavlov commented 1 year ago

In this case it does not really matter. Compiler knows length of both values at compile time, so it's able to generate efficient comparison code for simple a[..] == h[..] (after future migration to const generics you will be able to use a == h). In general, if you do not have a good reason do not use unsafe code, doubly so if you are not confident in your knowledge. When you work on micro-optimizations looking at generated assembly (e.g. by using https://rust.godbolt.org/) could be quite informative.

P.S.: I suggest using https://users.rust-lang.org/ for such questions.