Jump to content
  • Advertisement
Sign in to follow this  
cozzie

Sorting a std::vector efficiently

This topic is 2052 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,

 

I would like to know how/ what possibilities I have to rearrange a std::vector, assuming that I know in which order I want the elements to be rearranged. The sorting/ finding out the new order I've already covered and saved in a 'newIndex' int vector.The only possibility I thought of is making a copy of the original vector and then copy it back in the right order, but that feels like a waste of memory/ performance.

 

Can someone give me some directions?

bool CRenderQueue::SortBucketBlended()
{
	if(mEffectDataCreated)
	{
		size_t bucketSize = mRenderBucketBlended.size();

		std::vector<int>	indexTemp;	
		std::vector<int>	orderTemp;	
		std::vector<float>	distToCam;	
		
		indexTemp.resize(bucketSize);
		orderTemp.resize(bucketSize);
		distToCam.resize(bucketSize);

		for(size_t init=0;init<bucketSize;++init) orderTemp[init] = init;
		
		for(size_t renderable=0;renderable<mRenderBucketBlended.size();++renderable)
		{
			indexTemp[renderable] = renderable;
			distToCam[renderable] = mRenderBucketBlended[renderable].DistToCam;
		}

		sort(orderTemp.begin(), orderTemp.end(), [&](int a, int b)
			{ return distToCam[a] > distToCam[b]; });

		std::vector<int> newIndex;
		newIndex.resize(bucketSize);

		for(size_t results=0;results<bucketSize;++results)
			newIndex[results] = indexTemp[orderTemp[results]];

		// re-arrange the blended bucket based on newIndex?

		return true;
	}
	else return false;
}

Edited by cozzie

Share this post


Link to post
Share on other sites
Advertisement

I'm confused.  Why not just store pointers to the renderables in a vector?

std::vector<Renderable*> queue;
queue.clear();
FillQueue(queue);
std::sort(queue.begin(),queue.end(),SomeSortFunction);
for (auto i = queue.begin(); i != queue.end(); ++i) (*i)->Render();
Edited by Ryan_001

Share this post


Link to post
Share on other sites
  1. Store what needs to be sorted and nothing more.  Certainly not an entire “renderable”.  What is that anyway?  An entire mesh?  A part of a mesh?
  2. Single-responsibility principle.  A render-queue item is specifically designed to be a contextless collection of just the information needed to sort and determine the order of rendering of mesh parts.  It doesn’t know what a texture is, or a shader, mesh, vertex buffer, index buffer, etc.
  3. Never sort a render queue with std::sort().  It is neither stable (most important factor) nor fast enough thanks to pointer function calls on each compare.  Create a templated base class that uses < and == operators within its code and add these as inlined overridden operators to the render-queue item class/structure.
  4. Adding things to the render queue locally and sorting indices between them within that linear section of memory should always outperform a sort that needs to dereference 2 pointers on each compare, especially when what gets swapped is actually a 4-byte integer (no need to swap 64-bit integers just because you promote to 64-bit machines).

 

 

L. Spiro

Share this post


Link to post
Share on other sites

 

  1. Store what needs to be sorted and nothing more.  Certainly not an entire “renderable”.  What is that anyway?  An entire mesh?  A part of a mesh?
  2. Single-responsibility principle.  A render-queue item is specifically designed to be a contextless collection of just the information needed to sort and determine the order of rendering of mesh parts.  It doesn’t know what a texture is, or a shader, mesh, vertex buffer, index buffer, etc.
  3. Never sort a render queue with std::sort().  It is neither stable (most important factor) nor fast enough thanks to pointer function calls on each compare.  Create a templated base class that uses < and == operators within its code and add these as inlined overridden operators to the render-queue item class/structure.
  4. Adding things to the render queue locally and sorting indices between them within that linear section of memory should always outperform a sort that needs to dereference 2 pointers on each compare, especially when what gets swapped is actually a 4-byte integer (no need to swap 64-bit integers just because you promote to 64-bit machines).

 

 

L. Spiro

 

 

1) I don't know what the int's mean.  I assumed they were identifiers to renderable objects of some sort.  Its not like it matters...  If we're storing only what needs to be stored, then a unique id (aka a pointer) is sufficient.

 

2) That doesn't really apply here.  If I store id's to items, how is that different from storing pointers (and yes, I know a very complex Component Entity system might require id's, the OPs clearly not working with one...)?

 

3) I don't see why you would need a stable sort, but if you feel it is necessary std::stable_sort can be dropped in just as easily.

 

4) Whether you are storing int's or pointers, its the same thing performance-wise.  If you're sorting on data stored in an object (distance, shader usage, whatever) then you have to look that up somehow in the sort function.  Looking it up through a pointer is at least as fast, if not faster, than any other method.  If you didn't need object data in the sort, then using pointers is no slower.  Granted 64-bit pointers could be slightly slower to sort than pure 32-bit ints... perhaps... but the difference is negligible at best; and again if you have to look up data to do any compare, pointers are your best option.

Share this post


Link to post
Share on other sites
#1 and #2 are similar. “Store what you need.”
They are typically ID values, yes, but to shaders, textures, etc. Since a reasonable limit to the number of valid shader ID’s or texture ID’s is 65,535 concurrently, it is reasonable to use only 2-byte ID’s for these, half the bandwidth of a 32-bit pointer. This means on 32-bit systems you can put the ID’s next to each other in RAM and compare 2 at once, increasing the speed of the sort potentially dramatically.

And once again it performs the sort with as little knowledge about any graphics interfaces as possible; it uses the bare minimum of knowledge it needs to access, which is just a set of integral values for this purpose. Pointers would indeed be suitable too, but then you waste at least 16 bits and can compare only 1 structure member at once.

 

3) I don't see why you would need a stable sort, but if you feel it is necessary std::stable_sort can be dropped in just as easily.

  • So that things on top of each other don’t flicker, especially windshields or translucent objects with the same bounding box.
  • I said std::sort() is too slow.  If std::sort() is too slow, of course std::stable_sort() is too slow.  It would be better not to even use a render queue.

4) Whether you are storing int's or pointers, its the same thing performance-wise.

One word refutes this handily: Cache. Read my reply more carefully; I didn’t say talking about storing, I talked about accessing during a sort.
 

Granted 64-bit pointers could be slightly slower to sort than pure 32-bit ints... perhaps... but the difference is negligible at best

You know there is no such thing as negligible slowdown on a render queue right? Its whole purpose is performance.


#5: Render-queue items, which are tiny structures that hold all these ID’s and depth needed for sorting, also has another important feature that makes it necessary to use a separate structure rather than just a pointer to some modularity-breaking class: Pass number.
On multi-pass renders you should submit each pass to the render queue as a separate render-queue item structure, each with the correct shader ID and textures for that pass.
The object will be drawn once for each pass but the shaders will be properly sorted throughout (no behind-the-scenes changes between what should have been 2 objects drawn with the same shader) and overdraw on following passes will be minimized by having those passes delayed until their proper place in the queue.


L. Spiro

Share this post


Link to post
Share on other sites

Thanks all, for the valuable feedback.

For context, here's the Q_RENDERABLE struct (basically just some indices):

typedef struct Q_RENDERABLE			// renderable level; for filling render buckets
{
	int	Effect;
	int	Material;
	int	Mesh;
	int	Instance;
	int	Id;		
	float DistToCam;
} Q_RENDERABLE;

I really like the suggestion (LSpiro) to save the 'newIndex' with the sorted order of renderables and use that for rendering. I will simply not only pass the reference to the renderables vector to my draw function, but also the vector containing just the indices. That way there's no copying, sorting etc. needed within the vector of renderables. This also gives me flexibility when later on I'm sorting buckets on other criteria (For example opaque, from near to far to prevent overdraw etc.).

 

Besides this I read a lot of opinion on the way I'm currently 'generating' the newIndex / sorting based on the distToCam.

A few questions on this:

- what's a stable sort? (it has the exact same parameters and syntax and seems perfectly interchangable)

- would it really be worthwhile to create my own sort (like bubble sort or something)

- any other suggestions on how to improve coming to the newIndex?

(I can 'save' a bit my making the 3 vector's members instead of on the stack and do the initial filling just once, don't think that will bring much though)

(I believe using pointers directly to the dists to cam per renderable instead of copying them, doesn't bring much either)

Edited by cozzie

Share this post


Link to post
Share on other sites

This isn't the case in the OPs example.  He's using the indices to index into distToCam.

Based likely on one of my past posts and my first reply in which I suggested to sort indices rather than structures or pointers. All of my replies have assumed sorting of indices rather than pointers or objects.
 

But you suggest std::sort being too slow, and suggest using insertion sort instead?  That's VERY engine/game specific.

No actually it’s an all-encompassing fact. std::sort() (and friends) using a function callback cannot be faster than a templated inlined sort designed to call < and == operators (I said this already), and a stable sort is required to address temporal coherency.
An insertion sort that takes advantage of temporal coherency and uses inlined sorting comparison operators always beats std::sort() and friends; it’s only a matter by how much in a per-game or per-hardware basis. In my case it was 2.34 times faster in a large scene with about 100 sortable objects, each sorted 3 times for the different passes for shadows and normal rendering.

 

How more or less modular you want the system is up to you.

Except the render queue now knows what a “renderable” is instead of just what a 16-bit integer and a float is.

 

I prefer the easy solution unless profiling suggests otherwise.

Have you actually implemented my suggestions and profiled? The problem with your plan is that you have to have your profiler actually say to you, “By the way doc, this render queue could be faster.”
I’ve actually profiled various render queues quite a lot and made huge gains in performance over my first implementation, which may have been worse than having none at all (because I used std::sort()).

Nothing I have said until now is “opinion”. I implemented 5 more render queues after the first naive one and I am telling you from experience what I observed providing the most gains in performance. I also tried things I haven’t even mentioned here, such as a merge sort, because they ultimately provided no gains.

 

- what's a stable sort?

A sort that does not modify the orders of 2 objects that have the same sort value. If sorting by distance and 2 objects are exactly 25.0f units away, they will not be swapped inside of a stable sort.
 

- would it really be worthwhile to create my own sort

Combined with taking advantage of temporal coherence it gained me over 2.34 times the performance. Use an insertion sort.
 

(I can 'save' a bit my making the 3 vector's members instead of on the stack and do the initial filling just once, don't think that will bring much though)

Putting them on the stack means you are not taking advantage of temporal coherence, and not only that but you will allocate and deallocate memory every time the method is called. They should not be on the stack, for starters, even if they are fully cleared every call. Allocation is not just a “bit” of overhead.


L. Spiro

Edited by L. Spiro

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!