0

So I was reading few articles (and few questions on StackOverflow) about memory alignment and I understood why structs like this:

struct A
{
  char c;
  int i;
}

will have padding. Also it is clear that fetches from not aligned memory will be slower if processor can read only from aligned offsets.

But why processor can read only from aligned memory? Why it can't just read data from random address? You know, from Random-Access Memory...

Derag
  • 126
  • 1
  • 7

2 Answers2

0

I depends upon the processor. Some processors do not allow unaligned accesses at all. Other processors can, but it tends to be slower.

In your example (if the fields are packed and unaligned access it permitted, if the processor tries to read i, it usually takes fetches from memory to get it.

Some processors take the performance hit of multiple accesses to retrieve unaligned data. Others simply do not allow it.

user3344003
  • 20,574
  • 3
  • 26
  • 62
  • Yes, but why processors need to fetch multiple time when address is unaligned? RAM is just set of transistors, so why it can't read data to register from any address? – Derag Dec 21 '16 at 05:34
0

Processors are optimized to most common usecase: when data is correctly aligned. This is a reason why aligned reads are preferred.

But this doesn't answer your question. What makes aligned read more effective?

Answer is, that modern processors don't like to read from memory. They read from their cache which is in orders of magnitude faster.

Those caches organized using cache lines. Typical cache line is 64 byte, you can read exact values here. When you read aligned value, there is guarantee that value which size less or equal to cache line would be in single cache line. For unaligned value it is possible that part of the value in cache while other part accessible only from RAM.