2

I've got the following variable (simplified case):

std::array<std::array<float, 4>, 4> matrix;

I need to return this variable from a function in my program. I could either use std::unique_ptr or return it as a value (automatic vs dynamic memory)

Since the size of a float on my platform is 4 bytes, and there are 16 positions, size would be 16 * 4 = 64 bytes.

Dynamic memory without custom allocators etc can cause memory fragmentation in addition to being generally slow, so I got to wondering what the practical limit of passing around data as automatic memory vs dynamic memory could be? What size should I start using dynamic memory? Is the question unanswerable?

14
  • 4
    Why isn't a reference an option?
    – chris
    Oct 22, 2012 at 20:04
  • @chris Because that would require all variables to be initialized at the same level or above the place of usage. I'm planning on having say a function matrix<4, 4> create_projection_matrix(frustum, etc). It's somewhat inflexible... Or don't you agree?
    – Max
    Oct 22, 2012 at 20:16
  • the cost of passing stuff around has nothing to do with automatic Vs dynamic these are orthogonal issues. You could re-state your question as when is pass by value to expensive and thus pass by reference (which can be a pointer or a reference) start to happen. Oct 22, 2012 at 20:17
  • 2
    @icepack Actually, move semantics is more about moving resources (such as dynamically allocated memory), not actually moving value types as such. Please correct me if I am wrong.
    – Max
    Oct 22, 2012 at 20:45
  • 2
    @LokiAstari But when using a std::array<float, 4> there are no such resources involved, are there? To my knowledge it is automatically allocated.
    – Max
    Oct 22, 2012 at 20:48

5 Answers 5

2

If you are worried about the size of returning a structure like this as a result of an init function then I would not (caveats to that statement (you can always measure if you are unsure)).

All modern compilers are already doing RVO and NRVO optimization. As a result even if you return by value a copy is not being made. The compiler has already worked out that the result is going to a specific destination and has elided the copy and is building it in place at the destination.

Thus the size constraint is not really an issue.

Also with C++11 the concept of move semantics have been introduced. So you don't need to return by value but return via a move. In most std containers this just means swapping a couple of pointers (unfortunately this does not help with std::array) but in general case it works well.

So for me it would probably be a return by value. Though I may wrap that structure in a class. That way if reality bites and it does cost a lot I could change the class internally to compensate without changing the code.

2
  • 1
    A std::array<std::array<float, 4>, 4> has no pointers, it needs exactly 64 bytes like Max explained. Hence, move semantics does not give you any benefits. Copying such an array and moving such an array does the exact same thing, the 64 bytes have to be copied. Oct 22, 2012 at 21:34
  • @FredOverflow: Yes. I was being more general when I was talking about move semantics (I have tied to clean that up). The RVO and NRVO hold for std::array though. Oct 22, 2012 at 21:35
0

I do not think that you can cause any fragmentation by making 64 byte allocations. In my experience with large applications in 32 bits environment, allocations bigger than 16 MB may fail due to fragmentation issues. For allocations to cause fragmentation they should live for a long time. For server code, this is more than several days. In 64-bits env fragmentation is not likely to happen.

Passing parameter by value means creating a copy. This can be not efficient. Recommended work around is using references. There is no well known limit for the size.

From my experience I would recommend the following for a platform like PC:

  • size of the variable is less than 100 bytes - pass by value;
  • size of the var is greater than 1 KB - use reference and avoid copying;

The values is the middle are sort of grey zone where both decisions might be ok. Once again, there is no magic meaning in these numbers. Just some reasonable references.

I would recommend you to consider using references instead of heap allocations.

1
  • Is this relevant to the original question? Oct 22, 2012 at 20:13
0

Have you actually observed a performance degradation which you then traced to this code? Because if this is just a theoretical question, then I would suggest that you actually code things in the way that seems intuitive and natural.

After you have done that, and worked out all the kinks, you can run the program and see whether the performance you achieve is acceptable; if it isn't then you can set about optimizing the actual bottlenecks, instead of the imagined ones.

Donald Knuth said it best: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

0

Copying 64 bytes on stack is cheap. It's almost surely cheaper than allocating 64 bytes. If you use unique_ptr to a short lived variable allocated on heap you are almost surely losing efficiency.

If you simply call your function and use return value immediately it is fast. Only if you plan to propagate the matrix through a chain of matrix-returning functions your efficiency loss becomes significant. The feasibility of allocating memory and using unique_ptr depends on the number of times the data is re-returned more than it depends on the actual size of the data.

-1

Using a dynamic array for this is way overkill. You're not just allocating the 64 bytes to hold 16 floats. You're allocating 4 memory blocks for the array, each of which will have a header for heap management, and an array size per c++, and memory allocators internally will normally use blocks larger than what you ask for, often aligned on block boundaries.

Then you have the overhead for the structure that holds each array. Eg. each std::array is a class that holds a pointer to your objects, it is 8 bytes at minimum ( 4 for the pointer, and 4 for the array length ) x5 of them.

And you have no locality of reference. Each row in your matrix is possibly far away from each other in memory. If they were all next to each other they would get read in a single cache line.

You are way better off just using:

float matrix[4][4[

If you need it object oriented, wrap it in a class:

class Matrix44 
{
    float matrix[4][4];
}

This will be way more efficient.

4
  • Unlikely to be any difference in efficiency (in terms of usage patterns). Oct 22, 2012 at 20:18
  • 2
    std::array evaluates pretty much exactly to a standard (C-type static) array after compilation, I think.. The only thing dynamic would be the unique_ptr<64 bytes of array>.
    – Max
    Oct 22, 2012 at 20:19
  • ?? I guess not if you only use a few. But if he's asking a performance question he must expect to be using many. I'd guess a 4x4 matrix of floats would be for graphics- like a tree of transforms. He'd have thousands. Oct 22, 2012 at 20:19
  • @max: I checked it. You're right. It does compile down to 64 bytes contiguous in memory. That is it doesn't allocate separate buffers per row. Oct 22, 2012 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.