ZenQ
ZenQ copied to clipboard
Questions regarding struct fields order
Could you please explain:
- Why there is padding at the beggining of ZenQ structure?
// ZenQ is the CPU cache optimized ringbuffer implementation
ZenQ[T any] struct {
// The padding members 0 to 4 below are here to ensure each item is on a separate cache line.
// This prevents false sharing and hence improves performance.
_ cacheLinePadding
writerIndex atomic.Uint32
_ [constants.CacheLinePadSize - unsafe.Sizeof(atomic.Uint32{})]byte
readerIndex atomic.Uint32
_ [constants.CacheLinePadSize - unsafe.Sizeof(atomic.Uint32{})]byte
metaQ
_ [constants.CacheLinePadSize - unsafe.Sizeof(metaQ{})]byte
selectFactory[T]
_ [constants.CacheLinePadSize - unsafe.Sizeof(selectFactory[T]{})]byte
}
- Ordering of the slot type, as I think that on 64 bit system there would be waste of 32 bit in case of item being smaller than 32 bit as 64bit pointer must be 64 aligned. Moving writeParker to the top of the structure would solve the issue.
slot[T any] struct {
atomic.Uint32
writeParker *ThreadParker[T]
item T
}
Why there is padding at the beggining of ZenQ structure?
Simple reason would be the benchmarks ran faster with padding on top on 2 of my systems. I don't know how exactly but it happens.
Ordering of the slot type, as I think that on 64 bit system there would be waste of 32 bit in case of item being smaller than 32 bit as 64bit pointer must be 64 aligned. Moving writeParker to the top of the structure would solve the issue.
Got it, will make the changes. Also thanks for letting me know about this, really useful information.
Here you have some more info about alignment guarantees: https://go.dev/ref/spec#Size_and_alignment_guarantees https://pkg.go.dev/unsafe#Alignof https://go101.org/article/memory-layout.html
Ordering of the slot type, as I think that on 64 bit system there would be waste of 32 bit in case of item being smaller than 32 bit as 64bit pointer must be 64 aligned. Moving writeParker to the top of the structure would solve the issue.
fixed with https://github.com/alphadose/ZenQ/commit/a6352fb1261916318d8ecccedca495d9f8756ad5