ZenQ icon indicating copy to clipboard operation
ZenQ copied to clipboard

Questions regarding struct fields order

Open badochov opened this issue 3 years ago • 3 comments

Could you please explain:

  1. 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
	}
  1. 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
	}

badochov avatar Sep 10 '22 11:09 badochov

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.

alphadose avatar Sep 10 '22 17:09 alphadose

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

badochov avatar Sep 10 '22 17:09 badochov

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

alphadose avatar Sep 12 '22 12:09 alphadose