Rodousse / stbipp

A small size Image IO library based on stb_image. This has been archived due to a conflict of interest with my current employer.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Color] Add rvalue operator optimization

Rodousse opened this issue · comments

Is your feature request related to a problem? Please describe.
The color code handles only lvalues, except for the basic operations such as move assignment and move construction.
But when it comes to Color instantiated only in calculus... Well it is not that optimized.
Let's take a concrete example:

stbipp::Color4f col{0.0f};
col += 1.0f + stbipp::Color4f{1.0f, 2.0f, 3.0f, 4.0f} / 2.0f;

This gives us the right computation result on line 2, although the way the calculus is achieved:

  1. Instantiate Color4f and initialize with parameters {1.0f, 2.0f, 3.0f, 4.0f}
  2. Create a temporary Color4f that stores the result of the division by 2.0f and return it
  3. Create a temporary Color4f that stores the result of the previous operation and add 1.0f to it, then return it.
  4. Add the result to col.

As we can see there are 2 temporary allocation that are avoidable in steps 2 and 3.

Describe the solution you'd like
Well we can use the C++ wonderful rvalue feature, and have operator specialized when we manipulate rvalues in such operations (ref-qualified member functions):

stbipp::Color operator/(Real val) &&
{
  for(auto& val: m_data)
  {
    val /= 2.0;
  }
  return std::move(*this);
}

Et voila, no copy, no useless allocation!