Arduino - Optimising existing method for iterating

2019-07-28 05:21发布

问题:

Is there a more efficient and cleaner way of doing what the following method is already doing?

void sendCode(prog_uint16_t inArray[], int nLimit) {

  unsigned int arr[nLimit];
  unsigned int c;
  int index = 0;

  while ((c = pgm_read_word(inArray++))) {
    arr[index] = c;
    index++;
  }

  for (int i = 0; i < nLimit; i=i+2) {
    delayMicroseconds(arr[i]);
    pulseIR(arr[i+1]);
  }

}

This is in reference to an existing question I had answered.

Arduino - Iterate through C array efficiently

回答1:

There should be no need for the local arr array variable. If you do away with that you should both save temporary stack space and speed up execution by removing the need to copy data.

void sendCode(const prog_uint16_t inArray[]) {
  unsigned int c;

  for (int i = 0; c = pgm_read_word(inArray++); i++) {
    if (i % 2 == 0) { // Even array elements are delays
      delayMicroseconds(c);
    } else {          // Odd array elements are pulse lengths
      pulseIR(c);
    }
  }
}

This code assumes that the maximum integer stored in an int is greater than the maximum size of inArray (this seems reasonable as the original code essentially makes the same assumption by using an int for nLimit).