Reputation: 551
My performance with Boost ASIO on localhost seems slow. I'm using two reads/writes per data send/receive:
boost::asio::write(socket, boost::asio::buffer((char*)&data_size_network_byte_order, sizeof(uint32)));
boost::asio::write(socket, boost::asio::buffer(results->get_data(), data_size));
The reason is to send the size of the data first and then the data itself. Is this inefficient? If so what would be a more efficient way?
I have set no_delay to true and this helps a lot but isn't enough.
Upvotes: 0
Views: 1712
Reputation: 393134
First off, without measurements you're nowhere. Can you prove that it is unnecessarily slow?
Second, be sure to use scatter-gather and the composed write-operations supplied by ASIO. That eliminates your code as a source of inefficiency, and also generally removes room for error.
In that case
boost::asio::write(socket, boost::asio::buffer((char*)&data_size_network_byte_order, sizeof(uint32)));
boost::asio::write(socket, boost::asio::buffer(results->get_data(), data_size));
Could be
#include <boost/asio.hpp>
int main() {
using namespace boost::asio;
io_context io;
ip::tcp::socket s(io);
s.connect({{}, 6868});
std::string buf1 = "hello", buf2 = "world";
std::vector<const_buffer> bufs { buffer(buf1), buffer(buf2) };
auto written = write(s, bufs);
assert(written == buf1.size() + buf2.size());
}
This sends "helloworld", as you can see by the output of netcat
and the fact that the assert doesn't fire.
Upvotes: 1