2

The memory subsystem on a modern processor is restricted to accessing memory at the granularity and alignment of it's word size.

So can I assume that reading a char from memory should be as fast as reading a word (4 bytes)?

If the answer is YES than why do we even use char variables when coding instead of word variables (Other than the obvious type checking necessity).

Community
  • 1
  • 1
Kam
  • 5,878
  • 10
  • 53
  • 97
  • 1
    While it's been a long time since I had to worry about this level of optimization... its an interesting question nonetheless +1 – hammus May 23 '14 at 03:59
  • 1
    A processor will normally read an entire cache line from memory at a time. It would waste a *lot* of memory to allocate a full cache line if you only really needed to store one byte though. It would also (often) cause a substantial slow-down, because it would reduce the effective cache size to only one char per line. Packing the data makes the cache more effective. – Jerry Coffin May 23 '14 at 04:00
  • But regardless I will put in that cash line either a char or a word, so the scan would have to be done either way, no? – Kam May 23 '14 at 04:02

2 Answers2

0

Why do we use char variables? To avoid wasting memory. If you need 4 variables, you can fit 4 chars in a single word, but if you declared them as int it would take 4 words. If they only need to hold low numbers, all that extra memory is unnecessary.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

One reason I can immediately think of is that we just want a byte for an ASCII character.

const WORD* str = W"Hello World?";
               // ^ Some theoretical WORD-charactered string

Hehe.

And so because each character is just one byte, the processor would just have to do one fetch when getting, say, 4 characters.

Mark Garcia
  • 17,424
  • 4
  • 58
  • 94