Difference between using a serialized message and normal message type

asked 2021-05-14 01:50:08 -0500

BhanuKiran.Chaluvadi gravatar image

Hi,

I am going through the ros2 demos and came across talker.cpp and talker_serialized_message.cpp. I am wondering about the difference between the the usual way of publishing the data and serialized message publishing and which one is preferred ?

// talker.cpp
msg_ = std::make_unique<std_msgs::msg::String>();
msg_->data = "Hello World: " + std::to_string(count_++);
pub_->publish(std::move(msg_));

// talker_serialized_message.cpp
auto string_msg = std::make_shared<std_msgs::msg::String>();
string_msg->data = "Hello World:" + std::to_string(count_++);
auto message_header_length = 8u;
auto message_payload_length = static_cast<size_t>(string_msg->data.size());
serialized_msg_.reserve(message_header_length + message_payload_length);
....
....
pub_->publish(serialized_msg_);

Thank you

edit retag flag offensive close merge delete

Comments

This is just a guess so I won't add it as an answer yet, but the serialized_message.cpp route lets you pre-allocate the space for the message (reserve) thus avoiding the dynamic memory allocation incurred at the hidden serialization step of publish. This is important for safety critical programming where dynamic memory allocation is frowned upon due to the possibility of not being able to allocate memory during runtime. There may be some performance improvements by reusing the pre-allocated space of the serialized message. IMHO unless you are writing safety critical code or are optimizing, stick to the method shown in talker.cpp

djchopp gravatar image djchopp  ( 2021-05-14 14:30:49 -0500 )edit