20
In several code examples for the Arduino I note that there is almost no use of variables in local scope. One of the examples present in the IDE: Analog > AnalogInput
:
int sensorPin = A0;
int ledPin = 13;
int sensorValue = 0;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
sensorValue = analogRead(sensorPin);
digitalWrite(ledPin, HIGH);
delay(sensorValue);
digitalWrite(ledPin, LOW);
delay(sensorValue);
}
The variable sensorValue
is global, while its use is only within the function loop
. Another case is the library Moving-Average-Filter. A part of the code:
#define MAX_DATA_POINTS 20
class MovingAverageFilter {
public:
MovingAverageFilter(unsigned int newDataPointsCount);
float process(float in);
private:
float values[MAX_DATA_POINTS];
int k;
int dataPointsCount;
float out;
int i;
};
Here the members out
and i
are used only in process
, must be local:
float MovingAverageFilter::process(float in) {
out = 0;
values[k] = in;
k = (k+1) % dataPointsCount;
for (i=0; i<dataPointsCount; i++) {
out += values[i];
}
return out/dataPointsCount;
}
Using variables in this way seems absurd to me. Is it purposeful? If so, why?
The only possibility I can imagine is that the address of local variables would be known at compile time, so they can be accessed without taking into account the stack registrar. It really makes a difference?
But in the case of the class, I can’t see how it could be faster to read an object through the pointer this
than reading it in the stack, relative to the registered.
Another explanation might be to avoid having to allocate one stack frame for the function. But this allocation should be as simple as incrementing a registered one, I do not understand why it should be avoided. In addition functions that receive arguments will have a stack frame anyway.
Could having the variables this way facilitate identification in a possible memory dump? (just a kick - I’m a layman in low-level programming).
– Jônatas Hudler
Actually, it’s a more philosophical issue than performance. There may be a minimum difference in access to the stack frame or the fixed memory created for the global ones, but both are so close due to the nature of the applications that the difference is not even considerable. I prefer to continue with good practice and lose a few milliseconds of Runtime to lose hours of debugging.
– Guilherme Viebig
I don’t understand Uino, but what size is available for the stack? It is possible that the space in Uino for this is limited.
– Daniel C. Sobral