简体   繁体   中英

Pass boost::python::object by value or const reference?

Should I be passing boost::python::object objects to C++ functions by value or by const reference? I almost always pass around non-trivial objects in C++ via const reference. However, in the Boost Python documentation examples, they always pass boost::python::object by value. So I'm wondering if there's a reasoning behind that or they just did it that way to make the text easier to read or something.

boost::python::object is a trivial object.

Its just a wrapper around a PyObject*, so having a reference to a boost::python::object is basically just carrying around a pointer to a pointer. That's a bit of pointless indirection.

You do avoid incrementing reference counts by passing around the reference. But I'm going to guess that the indirection of using a reference hurts more then incrementing the reference count.

EDIT

I put together a benchmark:

void by_value(boost::python::object o)
{
    o + boost::python::object(1);
}

void by_const_ref(const boost::python::object & o)
{
    o + boost::python::object(1);
}

Results, when compiled with -O3

by-value:       9:215190247
by-const-ref:   5:764022989

Whereas with:

void by_value(boost::python::object o)
{
    for(int x = 0;x < 1000;x++)
    o + boost::python::object(1);
}

void by_const_ref(const boost::python::object & o)
{
    for(int x = 0;x < 1000;x++)
    o + boost::python::object(1);
}

I get:

by-value:       5:199017623
by-const-ref:   8:720536289

@eudoxous is correct, the write required to update the reference count is pretty expensive. However, the indirection caused by using a reference also has a cost. However, it seems smaller then I had anticipated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM