News for hackers. Stuff that matters.
Re:Great things about Rust that aren't just performance by sesm on Sunday January 12, 2025 @02:44PM (#42676256)
From Rust official docs:

`let lock = Arc::new(Mutex::new(0_u32));`

Doesn't this mean that Mutex introduces one more pointer?

For example, in Java every Object has a built-in mutex, adding some memory overhead in order to remove one extra layer of pointer dereferencing. As far as I understand, Rust introduces an extra layer of pointer indirection with Mutex, which can hurt performance significantly with cache misses.

Re:Great things about Rust that aren't just performance by dannymi on Sunday January 12, 2025 @03:11PM (#42676475)
I would suggest you read the source code of Mutex <https://doc.rust-lang.org/src/std/sync/mutex.rs.html#178-182> and then of UnsafeCell <https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html>.

So, the layout of Mutex<T> is the same as T and then some lock (well, obviously).

>Rust introduces an extra layer of pointer indirection with Mutex, which can hurt performance significantly with cache misses.

Why would there be an extra pointer dereference? There isn't.

Re:Great things about Rust that aren't just performance by sesm on Sunday January 12, 2025 @03:18PM (#42676530)
Thanks for the explanation!
Re:Great things about Rust that aren't just performance by oasisaimlessly on Sunday January 12, 2025 @03:11PM (#42676473)
> Doesn't this mean that Mutex introduces one more pointer?

No. That syntax is roughly equivalent to the following C++:

    auto const lock = std::make_shared<std::pair<std::mutex, uint32_t>>(
        std::piecewise_construct,
        std::make_tuple(),
        std::make_tuple(0));
Re:Great things about Rust that aren't just performance by sesm on Sunday January 12, 2025 @03:17PM (#42676524)
Thanks, that's the best explanation!
Re:Great things about Rust that aren't just performance by kbolino on Sunday January 12, 2025 @03:04PM (#42676407)
It is only Arc and not Mutex that allocates and thus has "extra" pointer indirection. A Mutex can live perfectly well on the stack, as long as it outlives the threads accessing it. Arc has to allocate, because it is meant to outlive the function that created it, and the only place to safely do that is on the heap.