#unaligned reads/writes

1 messages · Page 1 of 1 (latest)

arctic grotto
#

if i have a slice []align(1) u64, reads and writes done to it will be slower than a regular []u64 that has align 8, correct?

but those reads and writes to unaligned elements are still well defined as in it won't crash the program on any target right?

prime cargo
#

they will probably be slower, not guaranteed though. depends on the target. but yes they are well defined

#

i think on most CPUs unaligned access is either forbidden (so it needs to read a byte at a time and use shifts and ORs instead of a simple load) or slower than aligned ones

#

but some very simple CPUs like microcontrollers might have no alignment requirement/preference at all

viral marten
#

I believe on x64, unaligned reads and writes are the same speed as normal ones generally, but they will be slower if the read/write straddles a cache-line.

#

But indeed it depends on the CPU in question and how it's set up.

#

I think ARM CPUs can crash you for instance - though I seem to recall that is actually something that can be chosen by the OS as to whether it ultimately does or not.

prime cargo
#

the short answer is that zig makes it work and the only difference you may observe is performance

viral marten
#

Right

#

If you see align in a pointy type somewhere, then it means that Zig will emit machine instructions that are defined to not care about alignment.

prime cargo
viral marten
#

Indeed - many fewer instructions if aligned -- though, since it's RISC, I wonder how much difference that actually makes

#

RISC CPUs have fewer simpler instructions than CISC, AFAIK.
I seem to remember hearing something about them being able to execute those instructions faster than CISC could (at least as a baseline) simply due to less complexity and circuitry or whatever being necessary to do it.

prime cargo
#

the aligned version is 4 instrs: shift index left by 3, add to base address, load, return

viral marten
#

Indeed

#

I'd be interested in seeing what the timings would be in real code for that case

prime cargo
#

there are some cases in the RISC-V spec where they actually specify the instruction sequence you should use for various complex operations, so compiler devs can emit code that the cpu designers know to optimize for

#

i wonder if there is such a recommendation for unaligned accesses