How expensive is Rc<RefCell<...>> + .borrow_mut()?

.borrow_mut() branches based on the read-write of a isize and compares it to a given UNUSED constant (currently const UNUSED: isize = 0) before lending the RefMut struct.

It is not that expensive, imho (it's similar to writing one value of a slice: a bound check + a write)

.borrow_mut() should never panic, unless you violate the usage contract, such as when you index out of bounds.

Now, an interesting question regarding the branching would be, if instead of

        match borrow.get() {
            UNUSED => {
                borrow.set(UNUSED - 1);
                Some(BorrowRefMut { borrow })
            },
            _ => None,
        }

we could have:

#![feature(core_intrinsics)]
use ::std::intrinsics::unlikely;

unsafe {
    if unlikely(borrow.get() != UNUSED) {
        None
    } else {
        borrow.set(UNUSED - 1);
        Some(BorrowRefMut { borrow })
    }
}
3 Likes