r/programming • • Oct 06 '25

[deleted by user]

[removed]

153 Upvotes

218 comments sorted by

View all comments

Show parent comment

3

u/MEaster Oct 10 '25

Unfortunately this benchmark is worse. You are now trying to benchmark something that only takes a dozen or so cycles, which is incredibly difficult to do accurately. What you need to do is alter the benchmark so that the optimiser can no longer make assumptions about the state of the enum set or the variant of the enum being inserted.

For the enumset, based on your description Java's implementation might be doing a bit more work than Rust's enumset crate will after LLVM has optimised it, because Rust doesn't do the type check at runtime. With the Rust implementation, because the variant count is 7 the runtime representation will be a byte. Inserting a value and using the return value does the following if the variant and current state aren't known:

    // Copy the enum variant
	mov ecx, edx
	// Set the bit representing the enum variant.
	mov r9b, 1
    shl r9b, cl
	// Read the byte
    movzx ecx, byte ptr [r8]
	// Check if the bit is already set
    movzx eax, dl
    bt ecx, eax
	// If so, set the A register to true.
    setae al
	// Set the bit in the byte.
    or r9b, cl
	// Store the byte.
    mov byte ptr [r8], r9b

Note that due to the way modern processors work, much of this will happen in parallel. Java won't do better than that. It could match it, but this is the bare minimum work needed. Java could store the enum variant as the mask meaning it wouldn't have to do the shift to construct it, but then it would have to do an and-test pair instead of movzx-bt; I don't believe that would be faster though, because the biggest time sink here is the memory access and the shift will be done while that's executing.

2

u/davidalayachew Oct 10 '25

Unfortunately this benchmark is worse. You are now trying to benchmark something that only takes a dozen or so cycles, which is incredibly difficult to do accurately. What you need to do is alter the benchmark so that the optimiser can no longer make assumptions about the state of the enum set or the variant of the enum being inserted.

Too bad.

At this point, I think I am going to start phoning a friend, and try getting help from folks more knowledgeable about Java benchmarks. I might make a post to /r/java too, we'll see.

or the enumset, based on your description Java's implementation might be doing a bit more work than Rust's enumset crate will after LLVM has optimised it, because Rust doesn't do the type check at runtime.

Then it sounds like they are doing the same thing, because the type check is one of the first things that the JIT will optimize away. And I'm not sure I could stop the JIT from doing that.

But thanks for the help, this was very useful. I'll let you know if/when I get more info.