Philosophy: Instantiating inside vs outside loop
Posted: Wed Oct 18, 2023 6:17 pm
Hello IoT experts:
I see this in a lot of sample code:
vs...
Why do people do this?
It seems to me instantiating inside the loop puts a lot of pressure on the stack.
Rather, if it is instantiated outside loop...
. the memory gets allocated on the heap,
. it doesn't have to be recreated each time through the loop, (I understand creating stack space doesn't take a lot of time)
. we don't run the risk of using too much stack,
. loop should run faster.
Thoughts?
Thanks, Mark.
I see this in a lot of sample code:
- #include <ESP8266WiFi.h>
- loop {
- WiFiClient client; // WiFiClient inside loop
- if (client.connect(host, 80)) {
- ...
- }
- }
- #include <ESP8266WiFi.h>
- WiFiClient client; // WiFiClient outside loop
- loop {
- if (client.connect(host, 80)) {
- ...
- }
- }
It seems to me instantiating inside the loop puts a lot of pressure on the stack.
Rather, if it is instantiated outside loop...
. the memory gets allocated on the heap,
. it doesn't have to be recreated each time through the loop, (I understand creating stack space doesn't take a lot of time)
. we don't run the risk of using too much stack,
. loop should run faster.
Thoughts?
Thanks, Mark.