Protocol Buffer repeatedフィールドを読み込む2つの方法の効率比較

4927 ワード

テスト用の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を読み込むには2つの方法があります.
SubMsg sub_msg(int index); 

SubMsg* mutable_sub_msg(int index); // , Msg 

MutableTest.cc
#include "test.pb.h"

#include "Poco/Timestamp.h"

#include 
#include 

// ===  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()は明らかにずいぶん速くなった.
転載先:https://www.cnblogs.com/Leo-Forest/archive/2013/05/24/3096544.html