views:

248

answers:

3

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?

+3  A: 

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.

Don Neufeld
Thank you for the answer. I would really want to optimize it because, I do this operation every second, data size is 40,000 bytes and I do it for 3-4 days continuously.
Jack
Well, if you're CPU limited then by all means go ahead. If you're only XORing 40,000 bytes data every second I would say it's not worth it unless you're on an embedded system and trying to minimize power usage or something. On a modern laptop / desktop CPU that processing is negligible.
Don Neufeld
+4  A: 

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.
R Samuel Klatchko
+1  A: 

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

Dipstick
"On these processors non-aligned access causes a processor exception" - not necessarily. The ARMs I've used all did, but apparently some ARM processors don't trap, they just give you the wrong answer.
Steve Jessop
Thanks for mentioning about exception and wrong output. I never knew about this. My application is not going to be used with ARM though.
Jack