Question

Is there any advantage in doing bitwise operations on word boundaries? Any CPU or memory optimization in doing so?

Actual problem: I am trying to create XOR of two structure. Lets say structure-1 and structure-2 both of same size 10000 bytes. I leave first few hundreds bytes as it is and then start XOR of 1 and 2. Lets say I start with 302 to begin with. This will take 4 byte at a time and do XOR. 302, 303, 304 and 305 of both structure will be XORed. This cycle will be repeated till 10000.

Now, If I start from 304, Is there any performance improvement expected?

Was it helpful?

Solution

Yes, there are at least two advantages for using proper alignment:

  1. Portability. Not all processor support non-aligned numbers. For maximum portability, you should only use fully aligned (i.e. an N-byte integer starts at an address that is a multiple of N) numbers
  2. Speed. AFAIK, even a processor that supports non-aligned numbers is still faster with aligned numbers.

OTHER TIPS

Premature optimization is the root of all evil

Just do it the straightforward way, then optimize it if your profiler tells you it's important.

Yes, you will go faster if you're properly aligned. You'll go even faster if you use the SSE2 vector XOR instructions, where properly aligned you'll do it 16 bytes at a time and not pollute the cache. And it's highly unlikely that optimizing this is where you should be spending your time.

Some processors only allow 4-byte operations on 32-bit word boundaries (some allow them only on halfword boundaries).

On these processors non-aligned access causes a processor exception which - depending on CPU, OS and settings - will cause a process crash or just a lot of work for the OS.

On other processors (e.g. x86) you will just get the performance hit of having to do two reads and writes (plus a bit of shifting) per operation.

See link text to see problems with ARM CPUs

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top