-
-
Notifications
You must be signed in to change notification settings - Fork 84
Description
When reviewing my own code I stumbled upon the usage of std::string, which is a relatively expensive operation in a time critical section of my driver.
We could prevent allocation here by using std:string_view that passes the reference to the underlying data, which IMHO is a more efficient method for ISR-like callbacks. Basically I never really used std::string in my later code and converted back to const char * anyway.
I already tested the following variant of non-breaking API addition to NimBLEAdvertisedDevice:
#include <string_view>
std::string_view NimBLEAdvertisedDevice::getPayloadViewByType(uint16_t type, uint8_t index) const {
size_t data_loc;
if (findAdvField(type, index, &data_loc) > 0) {
const ble_hs_adv_field* field =
reinterpret_cast<const ble_hs_adv_field*>(&m_payload[data_loc]);
if (field->length > 1) {
return std::string_view(
reinterpret_cast<const char*>(field->value),
field->length - 1
);
}
}
return {}; // empty view
}
std::string_view NimBLEAdvertisedDevice::getNameView() const {
return getPayloadViewByType(BLE_HS_ADV_TYPE_COMP_NAME, 0);
}
(header change accordingly)
This would already carve 28 bytes out of my final binary with the small needed changes on the application side and should run faster, although I did no measurements yet.
That way it would be a non-breaking change and maybe you would consider to use this pattern in other parts of your library too.