定义测试用的Message:test.proto
message SubMsg { required uint32 n1 = 1; required uint32 n2 = 2; } message Msg { required uint32 n = 1; repeated SubMsg sub_msg = 2; }
[root@slayer xx]# protoc test.proto --cpp_out=./
从Msg里面读取SubMsgd有两种方法:
SubMsg sub_msg(int index); SubMsg* mutable_sub_msg(int index); //取出指针,可以修改Msg的内容
MutableTest.cc
#include "test.pb.h" #include "Poco/Timestamp.h" #include <iostream> #include <cstdlib> // === FUNCTION ====================================================================== // Name: main // Description: main function // ===================================================================================== int main ( int argc, char *argv[] ) { Msg msg; msg.set_n(0); for (int i = 0; i < 50000; ++i) { SubMsg* subMsg = msg.add_sub_msg(); subMsg->set_n1(i); subMsg->set_n2(i * 2); } int n1, n2; Poco::Timestamp ts; for (int i = 0; i < msg.sub_msg_size(); ++i) { SubMsg subMsg = msg.sub_msg(i); n1 = subMsg.n1(); n2 = subMsg.n2(); } std::cout << "msg.sub_msg(): " << ts.elapsed() << std::endl; ts.update(); for (int i = 0; i < msg.sub_msg_size(); ++i) { SubMsg* subMsg = msg.mutable_sub_msg(i); n1 = subMsg->n1(); n2 = subMsg->n2(); } std::cout << "msg.mutable_sub_msg(): " << ts.elapsed() << std::endl; return EXIT_SUCCESS; } // ---------- end of function main ----------
结果
[root@slayer xx]# g++ test.pb.cc MutableTest.cc -lPocoFoundation -lprotobuf [root@slayer xx]# ./a.out msg.sub_msg(): 6552 msg.mutable_sub_msg(): 1681 [root@slayer xx]#
用mutable_sub_msg()明显快了不少。