adafruit / Adafruit_BusIO

Arduino library for I2C & SPI abstractions
MIT License
290 stars 265 forks source link

Design intent question: Why malloc? #115

Closed antonysigma closed 1 year ago

antonysigma commented 1 year ago

Hi I like the Adafruit_BusIO library for its almost zero-overhead abstraction of the I2C and the DAC chip MCP4725. As an embedded programmer of constrained hardware, I wonder why the library invokes the new operator in the code?

In other words, is there a strong reason not to modify the code like the following, in order to avoid malloc at run-time?

--- a/Adafruit_SPIDevice.cpp
+++ b/Adafruit_SPIDevice.cpp
@@ -19,7 +19,7 @@ Adafruit_SPIDevice::Adafruit_SPIDevice(int8_t cspin, uint32_t freq,
   _sck = _mosi = _miso = -1;
   _spi = theSPI;
   _begun = false;
-  _spiSetting = new SPISettings(freq, dataOrder, dataMode);
+  _spiSetting = SPISettings(freq, dataOrder, dataMode);
   _freq = freq;
   _dataOrder = dataOrder;
   _dataMode = dataMode;
@@ -80,8 +80,6 @@ Adafruit_SPIDevice::Adafruit_SPIDevice(int8_t cspin, int8_t sckpin,
  *    @brief  Release memory allocated in constructors
  */
 Adafruit_SPIDevice::~Adafruit_SPIDevice() {
-  if (_spiSetting)
-    delete _spiSetting;
 }

 /*!
@@ -283,7 +281,7 @@ uint8_t Adafruit_SPIDevice::transfer(uint8_t send) {
 void Adafruit_SPIDevice::beginTransaction(void) {
   if (_spi) {
 #ifdef BUSIO_HAS_HW_SPI
-    _spi->beginTransaction(*_spiSetting);
+    _spi->beginTransaction(_spiSetting);
 #endif
   }
 }
ladyada commented 1 year ago

could be either, its the same memory and is on the heap either way