Optimizing the usage of std::vector in C++

  Рет қаралды 263,646

The Cherno

The Cherno

Күн бұрын

Patreon ► / thecherno
Twitter ► / thecherno
Instagram ► / thecherno
Discord ► thecherno.com/...
Series Playlist ► thecherno.com/cpp
Thank you to the following Patreon supporters:
- Samuel Egger
- Dominic Pace
Gear I use:
-----------------
BEST laptop for programming! ► geni.us/pakTES
My FAVOURITE keyboard for programming! ► geni.us/zNhB
FAVOURITE monitors for programming! ► geni.us/Ig6KBq
MAIN Camera ► geni.us/t6xyDRO
MAIN Lens ► geni.us/xGoDWT
Second Camera ► geni.us/CYUQ
Microphone ► geni.us/wqO6g7K

Пікірлер: 371
@MsJavaWolf
@MsJavaWolf 6 жыл бұрын
I really like C++. Many languages will abstract such things away, which can be very useful but I very often come back to C++ because I want that level of control.
@nexusclarum8000
@nexusclarum8000 5 жыл бұрын
I'd like to see a language that aims to do what C++ does but without keeping all the old C legacy stuff. Clean the language up a bit and make it less of a mess. Some of the standard library features should be language features and vice versa... and we'd have a really solid language for developing high performance applications using modern abstraction. Which is what C++ wanted to be from the beginning but got held down with trying to keep compatibility with C.
@swapode
@swapode 5 жыл бұрын
@@nexusclarum8000 You really should take a look at Rust. Just as close to the metal as C/C++ without all the baggage and some really good approaches to classic problems. It takes some getting used to, especially if you aren't over OOP yet, but I it's well worth it IMHO.
@Adrian-sb3bc
@Adrian-sb3bc 5 жыл бұрын
JK W no, that is not C#. C# is managed and abstracts everything, you have no control over anything.
@daddy9004
@daddy9004 4 жыл бұрын
@@nexusclarum8000 well there is a project held by MIT researchers that aims at exactly what you're talking about. It's called rust
@agrimg
@agrimg 4 жыл бұрын
@@nexusclarum8000 swift?
@michaelwright8576
@michaelwright8576 4 жыл бұрын
Optimization Strategy 1: (4:20) --> Construct the vertex in the same place as it will be stored. Rather than constructing it in the current method and then copying it to the vertex location. --> use emplace_back rather than push_back and only pass the parameter list for the constructor Ex. vertices.emplace_back(1, 2, 3); Optimization Strategy 2: (5:55) -->Remember to “know your environment”. --> If you know that you will need an array to store 3 vertex objects, define it as such so that it is not dynamically resized everytime it runs out of space. Ex. First define the vector, then use vertices.reserve(3); (on separate lines)
@sdwone
@sdwone 4 жыл бұрын
The std::vector also has a built in memory allocator that you can implement to get even more optimization. For instance, creating objects which are automatically aligned on the native CPUs cache line. For CPU intensive work, ensuring objects are cache aligned can gain HUGE benefits because the CPU can fetch data for processing more quickly if that data respects the cache line. So yeah, std::vector has plenty of nice features!
@lnx648
@lnx648 3 жыл бұрын
Probably late, but do you have any examples of how I could try to ensure cache optimization? Or sources to reference/learn? I've done a very simple test a long time ago and saw the time to complete the test reduce extremely thanks to a basic cache optimization, but not sure how to deal with more complex situations.
@CWunderA
@CWunderA 2 жыл бұрын
Thanks, good to know!
@DennisMartenssonOfficial
@DennisMartenssonOfficial 4 жыл бұрын
I think the biggest takeaway here is that you should ALWAYS try to reserve before you start pushing back elements into the container. Even if using emplace_back, the elements would be copied over in the case of a reallocation. So always call reserve before starting to push back. Even if you don't know exactly how many elements you will push back, a guesstimate is always better than not calling reserve at all.
@aeljandro2
@aeljandro2 2 жыл бұрын
This is gold for embedded systems!! Thank you so much!
@dariamagiera8685
@dariamagiera8685 5 жыл бұрын
your hair is goals 😂
@WelcomeToSex101
@WelcomeToSex101 7 жыл бұрын
Please do more! This is probably THE best series for c++ on youtube right now. Thanks a lot!!
@Mohamed-im3lq
@Mohamed-im3lq 4 жыл бұрын
Not only on KZbin, even paid courses are not even close to this tutorial
@aayushanand8285
@aayushanand8285 3 жыл бұрын
In my personal test in which I compared the usage of reserve() and resize(), it turned out that reserve() was indeed slower than resize() and also I had overloaded the new operator and from there I came to know that the reserve() method was allocating twice on the heap whereas the resize() method hit the heap only once. Why is this so? The compiler I used was g++ (MinGW) and compiled using std=c++17.
@FergusGriggs
@FergusGriggs 5 жыл бұрын
Why on earth would you bother using std::vector if you know the fixed number of elements? Surely you would just use an array?
@iDizzasTeR
@iDizzasTeR 5 жыл бұрын
Because arrays is C and vector is C++
@Luca-hn2ml
@Luca-hn2ml 4 жыл бұрын
@Peterolen Yep. Manually allocating dynamically using new or malloc is error-prone. And the stack is rather small. Thats why std::vector is still an option, even if the size is fixed.
@josiethompson5739
@josiethompson5739 3 жыл бұрын
7:40 does it though? does it really go up exponentially? that sounds linear to me...
@user-sl6gn1ss8p
@user-sl6gn1ss8p 3 жыл бұрын
It's even less than linear if vector grows by a factor (instead of just adding 1 to the capacity) : p
@Dead2098
@Dead2098 2 жыл бұрын
Yep, it is 2x linear :)
@anonymoussloth6687
@anonymoussloth6687 3 жыл бұрын
When we use emplace_back, does the vector object get constructed in heap?
@azizaziz-lw8wy
@azizaziz-lw8wy 2 жыл бұрын
Great video thx Cherno, but I got one question, how did we get 6 copies ? First copy because the instance was in the main memory then we had to copied to the heap or the allocate memory from the vector The second and third copies because the main and the resize the fourth ,fifth for same reasons, how about the six copy ?where did it came from? thanks for anyone in advanced whom answered me.
@tusharverma2454
@tusharverma2454 2 жыл бұрын
did you got your answer?
@strangeruler2317
@strangeruler2317 2 жыл бұрын
@aziz aziz Even am wondering the same, 3 for 3 object copy from stack to heap. 2 for extending the heap memory. Not sure about one more 😐
@andrefaustino5514
@andrefaustino5514 Жыл бұрын
It's easier to think on the push_backs. First push back -> 1 copy from main (and now you have 1 item in the list) Second push back -> 1 copy from main, 1 copy of the previous item (now you have 2 in the list) Third push back -> 1 copy from main, 2 copies because you have 2 items on the list (now you have 3) Until here, you have 6 copies with no optimization was made On one future forth push back -> 1 copy from main, 3 copies fifth push -> 1 copy from main, 4 copies
@aditya_sharma
@aditya_sharma 2 жыл бұрын
If emplace_back does the same thing as push_back but better then why do we need to use push_back? I mean why does push_back even exist?
@lukibukiboy4892
@lukibukiboy4892 6 ай бұрын
you gesturing so wyld with your hands so close to this cactus makes me feel really uncomfortable
@fabspark1631
@fabspark1631 Жыл бұрын
isn't the vector capacity increased by a multiple of 2 everytime enough space is not available??
@yavuzselimcagan5233
@yavuzselimcagan5233 2 жыл бұрын
It's amazing to see when cpu copies the members in the memory. And seeing that we reduce the amount of times we need to copy, it is soo nice.
3 ай бұрын
In fact the Cherno forgot an important point. Until 03:07, the Vertex pushed back in the container is an rvalue, and therefore will be moved (not copied), since the move constructor is implicitly defined. Upon redefining the copy constructor however, the implicit move constructor is deleted by the compiler. By wanting to see where the copy constructor is called, we cause our code to copy the Vertex instead of moving it(until we redefine the move constructor ourselves).
@teacup3000
@teacup3000 6 жыл бұрын
So is emplace_back now always the better option to push_back?
@Tarful2
@Tarful2 6 жыл бұрын
This was very informative. Awesome. I'd love to watch more optimization videos for general and often used c++ stdlib functions.
@nadavkedem4649
@nadavkedem4649 5 жыл бұрын
This is really great! Thank you! Can you please make additional optimization videos? Possibly even how to write a class with optimization in mind.
@jansuran5442
@jansuran5442 Жыл бұрын
7:36 I don't think the number of copies is going to be exponential, the formula is (n^2 + n) / 2 actually.
@benjaminli3808
@benjaminli3808 2 жыл бұрын
Why is it 6 then? If the first copy is from copying from the method to the vector, the second and third is from the copying of the second one and the extension of the length. Then wouldn't every subsequent one also just add two to the amount of copies.
@benjaminli3808
@benjaminli3808 2 жыл бұрын
I just added two more pushes (vertex(10,11,12) and vertex(13,14,15)) and these are the results when increasing the reserve value: reserve(1): 12 Copies reserve(2): 11 Copies reserve(3): 8 Copies reserve(4): 9 Copies reserve(5): 5 Copies Why is this happening?
@azizaziz-lw8wy
@azizaziz-lw8wy 2 жыл бұрын
I have the same question , did u get any answer for that?
@wheetcracker
@wheetcracker 4 жыл бұрын
3:42 wtf how on earth did you get your cursor to become 2 lines high like that
@wheetcracker
@wheetcracker 4 жыл бұрын
This changes everything.
@amrus3550
@amrus3550 4 жыл бұрын
Thanks. Helpful. Scott Meyer further elaborates by exploring when it's reasonable to expect emplacement to be better than insertion in his talk: "Scott Meyers - The evolving search for effective C++ - Keynote @ Meeting C++ 2014", at around the 20 minute mark.
@slayerfiend
@slayerfiend 3 жыл бұрын
why is there someone breathing in the background this scares me
@slayerfiend
@slayerfiend 3 жыл бұрын
@David Perkins sorry I have gills can’t be me
@ronaldweasly561
@ronaldweasly561 2 жыл бұрын
breathing from std::vector
@codergopher8270
@codergopher8270 4 жыл бұрын
C++, the very best programming language on earth. Way better than crippled turtle Python....
@carlosgarciavigoa7937
@carlosgarciavigoa7937 5 жыл бұрын
I'll make an echo of something that you already said... Get this into your head. YOU ARE THE BEEESSSTTTT. With you, everything is like a walk in the park. Thanks
@batman_1st
@batman_1st 5 жыл бұрын
So should we use emplace_back all the time instead of push_back? I see push_back on leetCode all the time.
@ineednochannelyoutube5384
@ineednochannelyoutube5384 5 жыл бұрын
I have read that emplace is liable to overrun memory limits, whilst push only uses implicit constructors and is thus safer.
@PrinceGupta-jo8lo
@PrinceGupta-jo8lo 5 жыл бұрын
@@ineednochannelyoutube5384 We need reserve and then emplace back for best performance
@roxferesr
@roxferesr 4 жыл бұрын
Glad someone asked this. I'm also curious!
@roxferesr
@roxferesr 4 жыл бұрын
@@ineednochannelyoutube5384 can you expand on this? Why is it unsafe to use explicit constructors?
@darkengine5931
@darkengine5931 4 жыл бұрын
I would rather people default to `push_back` and copy things in since swapping out the guts of what you are inserting to the vector may result in undesirable behavior at times. Simple example: vector v; string str = "..."; ... v.emplace_back(str); cout
@jkrw3540
@jkrw3540 5 жыл бұрын
After the capacity is 2, shouldn't after reallocation the capacity become 4. Doesn't it doubles every time? Although only 3 elements should be allocated.
@MrArbaz25
@MrArbaz25 5 жыл бұрын
The size of the vector is not doubled. At first the vector has a capacity of 1. As one copy constructor is called. After that when we add new vertex to it. The capacity is increased by one. So both vertex are copied to the new vector list. As two copy constructor are called. When we add a third vertex a new vector array is created with 3 size and 3 more copy constructor are called as the vertex from previous vector are copied over to the new vector array.
@johetajava
@johetajava Жыл бұрын
The push_back() method actually has O(1) time complexity. For larger sizes of the array, it will always double the size, or make it proportionally larger by some constant multiplier. So even if you can't reserve the space beforehand, it won't be as bad an issue, it won't cause any exponential time complexity. (It would, if it resized the vector before every insertion.)
@danielesquivel3155
@danielesquivel3155 4 жыл бұрын
La mejor serie de c++ que vi :)
@tomsku69
@tomsku69 6 жыл бұрын
Warning C4244 ('argument' conversion from _Ty to float possible loss of data). changed -> vertices.emplace_back(1, 2, 3); to -> vertices.emplace_back(1.0f, 2.0f, 3.0f);
@explorerofworlds512
@explorerofworlds512 4 жыл бұрын
I got the same thing. Didn't remember that I needed .0 at the end of my values for it to register my f properly. Thanks for your help
@lnx648
@lnx648 3 жыл бұрын
Yeah sure I know how to use a vector! Cherno: Think again.
@timgrohmann1388
@timgrohmann1388 7 жыл бұрын
Where‘s the "I kinda wanna date this guy" button when you need it?
@nissimhadar
@nissimhadar 5 жыл бұрын
This is the best explanation I have seen! I have also realized that watching videos teaches (me) much better than books.
@klarnorbert
@klarnorbert 4 жыл бұрын
One of the reason I don't like Bjarne Stroustrup's books, because it's like he's talking an alien language.
@manishgurawalia7625
@manishgurawalia7625 3 жыл бұрын
I love C/C++ , they r just mindblowing
@lucaaudino8013
@lucaaudino8013 3 жыл бұрын
Clear, precise, and super useful! Thanks, Cherno
@Traiden_
@Traiden_ Жыл бұрын
I am a C# programmer trying to understand C++ and it seems Lists in C# are exactly vectors as I understand it from this video. Cool!
@afterlife1578
@afterlife1578 6 ай бұрын
I asked my uni professor the difference between push_back and emplace_back and he told me they are basically the same, and didn't explain any further. Thank you Cherno
@jens6398
@jens6398 3 жыл бұрын
Looks like you're optimizing in debug mode... Copy construction will be optimized away by the compiler. In compiler explorer it gives identical results with optimizing flags.
@Desh-o7b
@Desh-o7b 3 жыл бұрын
Help me out guys! Whenever I am using "return new std::string[ ] {a,b}" It says " incomplete type is not allowedC/C++(70)". (it is mingw gcc).
@binyi1114
@binyi1114 Жыл бұрын
Just runned the emplace_back() but without .reserve(). It cames out that still no copied showed up. Can someone explain it?
@thememesarealive9813
@thememesarealive9813 Жыл бұрын
Fun thing that cherno does not mention is that if you set the copy constructor = to delete the code at the end of the video wont compile but why? Turns out emplace back might copy (not always) and so anything you pass into emplace back MUST have a copy constructor (just in case) the only fix I am aware of (that still performs 0 copies) is having a vector of unique ptr's to vertexes instead of a vectors of vertexes
@ekrem_dincel
@ekrem_dincel 3 жыл бұрын
Emplace_back seems meaningless to me here, aren't we pass the three numbers from stack anyway? Also, why the std::vector doesn't double the capacity when it is out of memory?
@khatharrmalkavian3306
@khatharrmalkavian3306 3 жыл бұрын
It's a silly example. In this case the arguments are literals, so they're actually stored in the compiled function itself rather than in the stack frame. Emplacement becomes very significant when you use more complex objects that are expensive to copy.
@mayukh_
@mayukh_ 4 жыл бұрын
But the question is that if we know our environments well and if we know how many object we shall be pushing, why I would go for a vector even. I would simply create array of objects right ??
@BinGanzLieb
@BinGanzLieb Жыл бұрын
In 6:11 you say, if we know "our environemnt" and planing to push three vertex objects, why not using an array with three elements instead?
@MrPepto93
@MrPepto93 2 жыл бұрын
There is no such thing as "more optimal" :D (this is my favourite way of annoying people :D)
@mohsenir69
@mohsenir69 3 жыл бұрын
Just a simple stupid question you won't use emplace_back for primitive type such as int or float is that right?
@dyrex27
@dyrex27 3 жыл бұрын
do you guys hear that there are background noises.. sounded like heavy breathing???
@paragggoyal1552
@paragggoyal1552 11 ай бұрын
it does not grow exponentially, it will always double so copies will be created 2*n times for n items being added.
@haru02w89
@haru02w89 Жыл бұрын
My main reason to learn C/CPP is actually be able to control that precisely what I want my computer to do
@haolinli296
@haolinli296 4 жыл бұрын
Wait, one the reason you would like to use vector is that you do not know the actually number of elements you need to push_back in advance, if you know the number why not use a standard array instead?
@ashutoshrautela3454
@ashutoshrautela3454 7 жыл бұрын
Please make an episode on templates as well
@atilacorreia
@atilacorreia 3 жыл бұрын
So push_back exists just to make people's lives easier but comes with a cost or do we actually get a real reason why we would create these extra copies?
@thewelder3538
@thewelder3538 Жыл бұрын
I thought this was going to be a look at how to write a good allocator for a vector, rather than just standard stuff everyone already knows. Writing an allocator for a vector to handle all of the cases it has to handle isn't trivial, this content is.
@themcscripter2111
@themcscripter2111 2 жыл бұрын
Interesting that it seems the copies is equal to the number pushed back factorial
@xrarach
@xrarach 4 жыл бұрын
Cool :) Thank you for the video, that actually was really helpful, learned something new.
@aronseptianto8142
@aronseptianto8142 3 жыл бұрын
so why would you even want to use push_back vs emplace_back?
@anas16d
@anas16d 3 жыл бұрын
Why do we even have push_back at first place?
@gavinw77
@gavinw77 7 жыл бұрын
So is this optimization or just understanding how the language / compilers / libraries work? Edit: I was also skeptical if these choices would make that much of a difference. Here are my finding after running some performance tests .. Test 1 : 10 push_backs / no reserve Test 2 : 10 push_backs / .reserve(10) Test 3 : 10 emplace_backs / .reserve(10) / passing Vertex(x,y,z) Test 4 : 10 emplace_back's / .reserve(10) / passing 1,2,3 primitives 54 copies / 42232 ave ticks 29 copies / 9025 ticks ave * 29 copies / 8835 ticks ave 0 copies / 36 ticks ave * * note that in different runs I would get wildy different results (upto x3 speed change).
@gebraten1999
@gebraten1999 7 жыл бұрын
pls do a like a cycle of videos f. e. c++, opengl, c++, opengl, ..
@kylefan8478
@kylefan8478 3 жыл бұрын
this is better than my uni programming course by far.
@fenilli
@fenilli 7 жыл бұрын
Cherno, so why would you use push_back()? there is a motive to use vector pushback function at all if it makes a copy of it?
@fixpontt
@fixpontt 7 жыл бұрын
Scott Meyers wrote an entire article about this topic in his book Effective Modern C++ (item41) claiming there are fringe cases (and often compiler dependent) where push_pack is faster.
@shadowmil
@shadowmil 7 жыл бұрын
Use push_back() when you want to insert an existing object instead of a new one. emplace_back() has to construct a new object at insertion time. Doing something like: myVector.emplace_back(vertex.x, vertex.y, vertex.z); *Technically* gets around doing a copy constructor, but it's going to have the same or worst performance profile as a copy constructor, and is a lot more code. So for example if I want to read a string from the console then insert that into a vector, I wouldn't get any benefit to using emplace_back(). I can use a move operation as well. For example: myVector.push_back(std::move(myString)); What this does is instead of calling a copy constructor, it calls a move constructor, which does a much lower level copy and is much faster, but leaves myString in an undefined state, and you should not use myString after doing a move operation on it. So in summary: std::vector v; v.emplace_back("New String"); v.push_back(ExistingStringIwantToContinueUsing); v.push_back(std::move(ExistingStringImDoneUsing);
@hsyn-yldz
@hsyn-yldz Жыл бұрын
My favorite part of this guy's videos : ) (9:26)
@deadyanothaikiropool1chait713
@deadyanothaikiropool1chait713 5 жыл бұрын
I looked up Me : wow gotta try that on the code! Another me : .....how am I going to adapt with this?
@faithium7077
@faithium7077 3 жыл бұрын
you gotta tell me that in java/c# copies are made for these reasons ? :o
@feraudyh
@feraudyh 7 жыл бұрын
Great, mate!
@ZihadJoy
@ZihadJoy 7 ай бұрын
"a professional knows what he is doing"
@hawkingT
@hawkingT 6 ай бұрын
std::cout
@GenericPhantom1
@GenericPhantom1 Жыл бұрын
Strategies on how to optimise your code so it runs faster.
@mohdharis131
@mohdharis131 5 жыл бұрын
As Ilari Vallivaara has said, the time of copying N elements in a vector is no where near exponential. It's linear. You will find that if you do the amortized analysis which he has explained in his comments. I would like to give a practical proof for it. Lets see how much time it takes to push 100M elements in a vector without reserving the space versus reserving the space. First, without reserving the space. #include #include using namespace std; #define MAX 100000000 int main() { vector subject; for(int i=1; i
@Aldric96
@Aldric96 5 жыл бұрын
Now try to do the same with a proper struct/class. It's misleading if you just use int ... the difference will be much bigger.
@RRFlash
@RRFlash 5 жыл бұрын
But I knew vector capacity gets doubled at every overflow....
@Adrian-sb3bc
@Adrian-sb3bc 5 жыл бұрын
Ok?
@abhijeetjain04
@abhijeetjain04 7 жыл бұрын
Why are we using copy constructor here ?? We are not using any pointers here !! so shallow copy can be done and it gives the same result ( using default constructor) as copy constructor!! so is there any specific reason ?? any one can help ?
@vidyabk1083
@vidyabk1083 6 жыл бұрын
He just wanted to show that the copy constructor is being called so many times by putting a print statement that's all :)
@FritsvanDoorn
@FritsvanDoorn 6 жыл бұрын
Hi Cherno, I would like to know where you get this knowledge from. A book? A course? Or have you analyzed the source code? Thanks for helping. You make good instructive videos.
@tonychristney2728
@tonychristney2728 4 жыл бұрын
I think we all get there eventually. This is just a massive short cut. The long way is a combination of reading the documentation, profiling and optimizing for performance. So axiom 0 is you need to be working in an environment where performance matters. Another video idea would be understanding how to use the built in STL sub-types, like std::X::value_type, std::X::size_type, etc. Another would be how to use std::vector::data() to get access to raw memory to be able to pass onto other APIs that don't know about vector, but still get the benefits of vector - like populating GPU buffers in D3D and OpenGL.
@Mitchinator1
@Mitchinator1 7 жыл бұрын
Great video! Thanks for this series! One question, how much should you reserve if you don't know the exact number? Let's say my vector might range between at least 16 and at max 128. Would it be better to reserve 16, or 128? Or would some where in the middle be better?
@beachforestmountain4269
@beachforestmountain4269 4 жыл бұрын
Do you know the answer to this question yet? I want to know the same thing.
@darkengine5931
@darkengine5931 4 жыл бұрын
One thing I'd suggest if you have a really critical path (ideally measured) and it resembles something like this: for (int j=0; j < some_huge_number; ++j) { vector v; v.reserve(???); // do something with v } If that's really critical I'd recommend instead to just hoist the vector out of the loop. vector v; v.reserve(some_large_size); for (int j=0; j < some_huge_number; ++j) { // do something with v v.clear(); } In this case, you can more confidently reserve a larger capacity for the vector if you even reserve at all, because you are only paying for the heap allocation involved with reserving once for the entire massive loop. The 'clear' method of vector doesn't free its underlying dynamic array. It keeps whatever capacity it had before clear was called. That'll wipe out almost the entirety of both the linear-time copies or moves involved with reallocating along with the heap allocations involved with reallocating and you don't have to spend so much time guessing and fiddling around with some optimal capacity for reserve. Or you can even avoid reserving once you have things this way, reusing the same vector for each loop iteration, and the cost of not reserving in advance will probably be negligible since the vector's capacity will quickly start to fit the common case requirements of each loop iteration.
@khatharrmalkavian3306
@khatharrmalkavian3306 3 жыл бұрын
If you're not worried about memory consumption (do the math) then just reserve 128. Otherwise be aware that most implementations of vector increase their reserve length by 50% (rounded up) each time they reallocate. So the question becomes how many reallocations you're prepared to tolerate vs how much unused memory you're prepared to tolerate. In the 16 to 128 case, if you start at 16 then 128 would need 6 reallocations. If you start at 38 then it's only 3. The case that you really need to worry about is when you have a vector that can become arbitrarily large very quickly, since that's the worst for performance. In that case it's best to experiment a little to try and determine the average peak size under normal use and just reserve that amount. All that having been said, this is generally only a significant issue in code that is handling massive sets of complex data or in code that is simply malformed and should be refactored rather than optimized. (Lack of move-constructors can be a culprit here.) Remember to avoid premature optimization: don't spend more time optimizing than time you're saving unless there's a systematic reason for it.
@ABaumstumpf
@ABaumstumpf 3 жыл бұрын
A bit late but... Nobody can really say. Khatarr already gave some good information as well. Anyways. you have anywhere from 16 to 128 Elements? Are the big? how often do you get 16, 64, 128 or any other number of elements? Are you constraint by memory or CPU-time? Is performance in that actually critical or would it just be a nice to have? If performance is not critical then just don't. Things like printing out the elements the the console are so much slower that any change you do to the reservation become irrelevant. If you are constraint by memory then you also do not want to reserve more than you need. If you know that most of the time it will be, say for example, less than 50 elements and you need that performance - than reserve it for a bit more than that so that 90% of the time it is fine. Or if you objects are expensive to construct, copy and delete. It is also mostly the case that when you feel the need to ask such a question there are 3 things at play: You do not know the exact situation your program is in, you do not really need any higher performance, and the things you are using are so simply that just reserving even 500 Elements is no problem.
@serkanozturk4217
@serkanozturk4217 Жыл бұрын
Personal Notes: - vertices.reserve(44) allocates memory that can hold 44 vertex object -vertices.push_back((1,0,0) and vertices.push_back(Vertex(1,0,0)) does unnecessary copying(and creating) of Vertex object, use vertices.emplace_back(1,0,0) instead not to copy unnecessarily. -I am bored and hurried, don’t trust 100% what I just said
@rcookie5128
@rcookie5128 7 жыл бұрын
ahh.. gotta love optimization.. :) indeed so satisfying if you clean up and let your programm perform better
@gavinw77
@gavinw77 7 жыл бұрын
Don't C++ compilers automatically unroll as they optimize?
@rcookie5128
@rcookie5128 7 жыл бұрын
hmm could be true, don't know that actually (learned unrolling in another language though..)
@chlorobyte_projects
@chlorobyte_projects 3 жыл бұрын
Yeah, it shouldn't be needed in C++.
@Mr4Eyee
@Mr4Eyee 2 жыл бұрын
Wtf is this Goku hairstyle xD
@ParhamSalamati
@ParhamSalamati 7 ай бұрын
This was BY FAR one of the most awesome things I've learned this month regarding std lib optimization in C++! You're a LEGEND
@prathmesh.kallurkar
@prathmesh.kallurkar 5 жыл бұрын
This was EXACTLY what I needed right now. Am using a global vector where each element is HUGE - in GBs. I was initializing this vector through resize (size, def_val). def_val being huge messes up with the stack. The reserve and emplace_back will help me save copy cost and help me create elements on the heap.
@carlsb3rg
@carlsb3rg 5 жыл бұрын
If you need even more control in some resource rich situation, check out std::allocator in the header. It is what vector and all other containers use to manipulate their storage, but you can get an even finer grain of control by using it yourself.
@jcdentonunatco
@jcdentonunatco 6 жыл бұрын
That was beautiful, thanks!
@iaroslavsorokin4318
@iaroslavsorokin4318 4 жыл бұрын
I recently made an implementation of a vector container in C (just because where I'm currently doing my studies we are writing in C and are not allowed to use any C library functions), and someone told me that the way they are resizing - is by multiplying its capacity by 2 every time, but now I see this is not the case. Why not?
@zoriiginalx7544
@zoriiginalx7544 4 жыл бұрын
It should be according to the standard if I'm not mistaken. Refer to cppreference for implementation details on these containers.
@khatharrmalkavian3306
@khatharrmalkavian3306 3 жыл бұрын
It's not specified by the standard. Many implementations increase by 50%, some just double it. The mathematically optimal rate of expansion is the golden ratio, which is 1.6 something, but 1.5 and 2 are faster to calculate.
@MrCarburettor
@MrCarburettor 3 жыл бұрын
Absolutely superb!! Additionally you talk like Brüno... This must be the best c++ series in all German spoken countries except Germany!!
@PulkitMalhotra
@PulkitMalhotra 3 жыл бұрын
c pillow like channel logo impressing
@cprn.
@cprn. 3 жыл бұрын
So... If `Texture` is a custom class, I cannot really wrap around `std::vector` to make it more general because I'd have to know the signature of `Texture` constructor in advance in order to pass its parameters to whatever calls `emplace_back()`. Or is there some templates magic that handles this? (example is hypothetical so it might be lacking but I tried to imagine a real life scenario and hopefully this is enough to understand my doubts)
@Norhther
@Norhther 4 жыл бұрын
How we can optimize something like std::vector values ?
@thomaslinssen1426
@thomaslinssen1426 4 жыл бұрын
8:09 isn't this actually less efficient than just Vertex(1,2,3) ? Since it has to do an implicit conversion now? That's what you explained in that other video
@JohnnyPhoenix
@JohnnyPhoenix 4 жыл бұрын
No implicit conversion going on: vector already knows the type of the object to construct.
@khatharrmalkavian3306
@khatharrmalkavian3306 3 жыл бұрын
It's not converting because there's no object to convert from. It's actually constructing the object in place within the vector.
@kartikchauhan3382
@kartikchauhan3382 3 жыл бұрын
I've so many questions.
@torbjornstorli2880
@torbjornstorli2880 4 ай бұрын
What a great video! Loved the way you showed how to optimize a vectors memory footprint. These are the types of details that I have not yet seen in any other c++ videos on KZbin. Wonderful job. Thanks a lot!
@erikgiesenloo1871
@erikgiesenloo1871 3 жыл бұрын
"reserve" vs "resize" is a noob trap
@danibarack552
@danibarack552 3 жыл бұрын
I wouldn't have guessed that push_back makes a copy of the instance, coming from java that is very strange
@chiefolk
@chiefolk 3 жыл бұрын
is it a good idea to use emplace_back() for primitive data types, because i don't know how construction of primitive datatypes work.
@khatharrmalkavian3306
@khatharrmalkavian3306 3 жыл бұрын
It's safe. Primitives only "technically" have construction. That is, they can use construction semantics, but the compiler just does the obvious thing and assigns the value normally. Primitives, by definition, don't have actual constructors, so there's no underlying function call. The compiler will just "do the right thing".
@dealvin
@dealvin 2 жыл бұрын
Reserve and emplace_back
@tens0r884
@tens0r884 2 жыл бұрын
What if you have instances of the vector class instantiated already? Surely we dont pass all their attributes individually into emplace_back
@TheFlyingMonkey200
@TheFlyingMonkey200 3 жыл бұрын
Why does he always make a vertex class? Just wondering... anyone know?
@CWunderA
@CWunderA 2 жыл бұрын
This was very useful, but how do you do strategy #1 (size the vector beforehand) if you don't know how much memory/what size you need? A typical case i run into is reading in a file. Often the file has an unknown number of lines (ie vector size needed unknown) or the file has variable line lengths (ie size of each vector element unknown)
@D3r3k2323
@D3r3k2323 4 жыл бұрын
Would the compiler automatically do these optimizations if you're not in the debug build?
@181Ravikiran
@181Ravikiran 5 жыл бұрын
replace push_back() with emplace_back() for optimization
@jacobw703
@jacobw703 5 жыл бұрын
Watch the whole video before responding.
@181Ravikiran
@181Ravikiran 5 жыл бұрын
@@jacobw703 which part you didnt watch ... ?
@frhowe08
@frhowe08 4 жыл бұрын
Not sure which Ide you're using for sure but on mac I cannot view the memory being allocated like this. Tried on vsCode visual studio and xcode
@bundlesofun9568
@bundlesofun9568 2 жыл бұрын
i like to compare c++ versus c# to a manual transmission versus an automatic. With great power comes great responsibility, and great reward!
Local Static in C++
7:40
The Cherno
Рет қаралды 185 М.
Dynamic Arrays in C++ (std::vector)
14:14
The Cherno
Рет қаралды 380 М.
GIANT Gummy Worm Pt.6 #shorts
00:46
Mr DegrEE
Рет қаралды 99 МЛН
Will A Guitar Boat Hold My Weight?
00:20
MrBeast
Рет қаралды 256 МЛН
Как подписать? 😂 #shorts
00:10
Денис Кукояка
Рет қаралды 8 МЛН
Spongebob ate Patrick 😱 #meme #spongebob #gmod
00:15
Mr. LoLo
Рет қаралды 18 МЛН
Type Punning in C++
13:20
The Cherno
Рет қаралды 157 М.
Threads in C++
11:35
The Cherno
Рет қаралды 362 М.
Function Pointers in C++
12:41
The Cherno
Рет қаралды 389 М.
BENCHMARKING in C++ (how to measure performance)
14:52
The Cherno
Рет қаралды 157 М.
Copying and Copy Constructors in C++
20:52
The Cherno
Рет қаралды 429 М.
lvalues and rvalues in C++
14:13
The Cherno
Рет қаралды 315 М.
Move Semantics in C++
13:10
The Cherno
Рет қаралды 294 М.
I Rewrote This Entire Main File // Code Review
16:08
The Cherno
Рет қаралды 159 М.
The Dark Side of .reserve()
18:50
Logan Smith
Рет қаралды 150 М.
GIANT Gummy Worm Pt.6 #shorts
00:46
Mr DegrEE
Рет қаралды 99 МЛН