Python Protobu中高效的消息字段设置

2024-06-28 19:57:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个Python项目中使用Protobuf(v3.5.1)。我的情况可以简化为:

// Proto file

syntax = "proto3";

message Foo {
    Bar bar = 1;
}

message Bar {
    bytes lotta_bytes_here = 1;
}

# Python excerpt
def MakeFooUsingBar(bar):
    foo = Foo()
    foo.bar.CopyFrom(bar)

我担心.CopyFrom()的内存性能(如果我是正确的,它是复制内容,而不是引用)。现在,在C++中,我可以使用类似的:

^{pr2}$

根据生成的源,它看起来不需要复制任何内容:

inline void Foo::set_allocated_bar(::Bar* bar) {
  ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
  if (message_arena == NULL) {
    delete bar_;
  }
  if (bar) {
    ::google::protobuf::Arena* submessage_arena = NULL;
    if (message_arena != submessage_arena) {
      bar = ::google::protobuf::internal::GetOwnedMessage(
          message_arena, bar, submessage_arena);
    }

  } else {

  }
  bar_ = bar;
  // @@protoc_insertion_point(field_set_allocated:Foo.bar)
}

Python中是否有类似的功能?我查看了Python生成的源代码,但是没有发现任何适用的代码。在


Tags: 内容messageifbytesfoogooglebarprotobuf
1条回答
网友
1楼 · 发布于 2024-06-28 19:57:32

当谈到大的stringbytes对象时,Protobuf似乎很好地描述了这种情况。下面的过程,这意味着在创建一个新的Bar对象时,二进制数组是通过引用复制的(Python bytes是不可变的,因此它是有意义的):

def test_copy_from_with_large_bytes_field(self):
    bar = Bar()
    bar.val = b'12345'
    foo = Foo()
    foo.bar.CopyFrom(bar)

    self.assertIsNot(bar, foo.bar)
    self.assertIs(bar.val, foo.bar.val)

这解决了我的大bytes对象的问题。但是,如果有人的问题出在嵌套的或重复的字段中,这将不会有帮助-这样的字段是逐字段复制的。这是有道理的-如果一个人复制了一条信息,他们希望两个独立。否则,对原始邮件进行更改将修改复制的邮件(反之亦然)。在

如果Python原型BuffF中有类似于C++移动语义(https://github.com/google/protobuf/issues/2791)或^ {CD6>}的任何东西,那么这将解决它,但是我不知道这样的特性。在

相关问题 更多 >