Electronic – Should I refactor the C code to optimise it for an embedded microcontroller

cmicrocontrollerprogramming

Below is some code implemented on an 8 bit microcontroller.

The following comment was posted to another question:

As your code doesn't use the i variable, why not just while(length--)
instead of the first for loop?

It suggests changing the for(..) loop for a while(..), will this make any practical difference to how optimised the code is for an embedded microcontroller?

uint32_t MyFunction(uint32_t crc, uint8_t *buffer, uint16_t length) {
    for (uint16_t i=0; i < length; i++) { 
        crc = crc ^ *buffer++; 

        for (uint16_t j=0; j < 8; j++) { 
           if (crc & 1) 
              crc = (crc >> 1) ^ 0xEDB88320; 
           else 
              crc = crc >> 1; 
        } 
    } 

   return crc; 
}

Note: I wrote this question and answered it myself after posting a comment earlier this week. That comment was upvoted but I felt I should back it up with some actual testing. Other answers would be useful, but this was intended as generic proof of a point rather than a specific question about the algorithm.

Best Answer

The classic three rules of optimization:

  1. don't.
  2. don't yet.
  3. profile before optimizing.

It doesn't hurt to write clean tidy code in the first place but premature optimization is a waste of time and effort that could more fruitfully be spent elsewhere.