Saving to a variable faster than saving to an array?

If I am saving 15 unsigned int values at intervals of 10ms, is there a difference in time spent on the operation if save to a variable versus save to an array, on the order of one tenth of a milli? I prefer to store my 15 time stamps in an array rather than 15 variables. But I don't want to miss or delay a time stamp if Arduino needs to spend a lot of time for writing to an array. My values are in range of 5-1,000 millis and arrive as quickly as 10ms apart.

Thanks.

What hw you running on?

Reading/writing in a variable or in an array takes like a miCROsecond or less, so don't worry about speed, just use array, even if it's slightly slower than individual variables you will never notice a difference

1 Like

A write to a scalar variable and an element in an array will be the virtually exact same operation in terms of time.... Note that depending upon which CPU range you are using, the store instructions may execute in 1 or 2 clock cycles - but at 16MHz (the speed of 8 bit Arduinos), that is 16 million writes or 8 million writes per second - which is way faster than your incoming data rate.

In the case of an array if you use a variable to index the particular element, then there will be an additional operation being an addition of the starting address of the array and the index multiplied by the size of the elements in the array. This will take a small number of clock cycles (sort of in the range of 10 clock cycles plus or minus).

Now if you are running at 16MHz, then that means that a write to a specific array element will as I said before the same as a write to a scalar variable, but there will be an addition of maybe 10 clock cycles. That will be around the 1 micro second mark (or 1/1000th of a millisecond).

So it is unlikely that you will miss any incoming data reads due to the fact that you are writing to an array.

Indeed writing to an array will likely be faster than defining 16 scalar variables and executing a complex if/then/else statement or case statement to work out which of the 16 scalar variables you need to update then updating that particular variable. The same would go for when you need to read them back to do whatever you need to do with them.

Arduino Uno

Big Thanks - exactly the answer and explanations that solve my problem.
I'll use an array, the difference is of no significance.
Really appreciated.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.