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

Поділитися
Вставка
  • Опубліковано 21 вер 2017
  • Patreon ► / thecherno
    Twitter ► / thecherno
    Instagram ► / thecherno
    Discord ► thecherno.com/discord
    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

КОМЕНТАРІ • 373

  • @MsJavaWolf
    @MsJavaWolf 6 років тому +424

    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.

    • @EmbeddedSorcery
      @EmbeddedSorcery 5 років тому +18

      I miss real languages... Been in LabVIEW world for a while. The idea of "optimizing" there would be laughable. Talk about abstraction ...

    • @nexusclarum8000
      @nexusclarum8000 5 років тому +64

      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.

    • @EmbeddedSorcery
      @EmbeddedSorcery 5 років тому +4

      @@nexusclarum8000 I think that's what C# was supposed to be wasn't it? I've been wanting to learn that a little better.

    • @swapode
      @swapode 5 років тому +30

      @@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 4 роки тому +21

      JK W no, that is not C#. C# is managed and abstracts everything, you have no control over anything.

  • @michaelwright8576
    @michaelwright8576 3 роки тому +128

    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)

  • @WelcomeToSex101
    @WelcomeToSex101 6 років тому +124

    Please do more! This is probably THE best series for c++ on youtube right now. Thanks a lot!!

    • @Mohamed-im3lq
      @Mohamed-im3lq 4 роки тому +22

      Not only on UA-cam, even paid courses are not even close to this tutorial

  • @sdwone
    @sdwone 4 роки тому +50

    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 роки тому +9

      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 роки тому +1

      Thanks, good to know!

  • @DennisMartenssonOfficial
    @DennisMartenssonOfficial 4 роки тому +18

    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 роки тому +10

    This is gold for embedded systems!! Thank you so much!

  • @torbjornstorli2880
    @torbjornstorli2880 2 місяці тому

    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 UA-cam. Wonderful job. Thanks a lot!

  • @lucaaudino8013
    @lucaaudino8013 3 роки тому +3

    Clear, precise, and super useful! Thanks, Cherno

  • @dmytroboiko1
    @dmytroboiko1 8 місяців тому

    Super cool! I hope there is a lot more stuff like this later on in this series. Thanks Cherno.

  • @Katelomjaria
    @Katelomjaria 3 роки тому

    I love your tutorials :d you explain it perfectly. helped me a lot. i plan to watch the whole series to understand cpp better.

  • @Tarful2
    @Tarful2 6 років тому +8

    This was very informative. Awesome. I'd love to watch more optimization videos for general and often used c++ stdlib functions.

  • @abhisheksa6635
    @abhisheksa6635 11 місяців тому

    Good optimisations and clear show of how it helps in running fast, keep going.

  • @nadavkedem4649
    @nadavkedem4649 4 роки тому +7

    This is really great! Thank you! Can you please make additional optimization videos? Possibly even how to write a class with optimization in mind.

  • @svenbtb
    @svenbtb Рік тому

    This rules. Thank you for showing clearly how you can look for ways to optimize and for giving such an easy to follow example, and thank you for all your videos in general. Trying really hard to learn C++ on my own and your content is more helpful than the MIT classes that are online. It's easy to follow, easy to digest, assumes that the viewer is competent, isn't condescending at all to people who are new to C++, all while explaining everything clearly.

  • @jcdentonunatco
    @jcdentonunatco 5 років тому +3

    That was beautiful, thanks!

  • @xrarach
    @xrarach 4 роки тому +2

    Cool :) Thank you for the video, that actually was really helpful, learned something new.

  • @LucidStew
    @LucidStew 6 років тому

    Nice video. A couple of really easy and effective tips there. Thanks.

  • @mcjustin1
    @mcjustin1 3 роки тому

    Very nice taste of optimizations to come. Can't wait for the game engine series!

  • @mikedoeren5960
    @mikedoeren5960 Рік тому

    Sick video - thanks Cherno!

  • @amrus3550
    @amrus3550 4 роки тому +3

    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.

  • @ilkercankaya3779
    @ilkercankaya3779 3 роки тому

    My man your channel is a blessing from c++ gods. My c++ code runs like a rocket now thx bro

  • @shruikan123456789
    @shruikan123456789 6 років тому +2

    incredible video, it s really teaching a lot!

  • @YashArora721
    @YashArora721 5 років тому

    Man this was great. Thanks dude.

  • @unknownunknown6531
    @unknownunknown6531 6 років тому

    So much quality in this video

  • @sahilsharma2952
    @sahilsharma2952 4 роки тому

    This C++ series is so great. Its free, to point and easy to understand.

  • @lmagiczlukas4891
    @lmagiczlukas4891 3 роки тому

    Thank you so much for the helpful video!

  • @feraudyh
    @feraudyh 6 років тому +8

    Great, mate!

  • @mohamedhussien4013
    @mohamedhussien4013 Рік тому

    You go to details bro.
    Thank you so much.

  • @SuhailKhan-vr6ik
    @SuhailKhan-vr6ik 6 років тому

    This video is gold! More optimization videos pls

  • @joshuastein1888
    @joshuastein1888 3 роки тому

    you're really good at this!

  • @ayanarif1
    @ayanarif1 5 років тому

    Thanks man!!!! This is one of the best...

  • @DOCtorActoAntohich
    @DOCtorActoAntohich 4 роки тому

    The best tutorials ever. Thank you!

  • @ParhamSalamati
    @ParhamSalamati 4 місяці тому

    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

  • @refikalpertuncer8512
    @refikalpertuncer8512 3 роки тому

    This is by far the best cpp tutorial video, made by Cherno.

  • @danielesquivel3155
    @danielesquivel3155 4 роки тому +5

    La mejor serie de c++ que vi :)

  • @hengzhao5953
    @hengzhao5953 5 років тому +1

    Best C++ tutorial video ever!

  • @yavuzselimcagan5233
    @yavuzselimcagan5233 2 роки тому +4

    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.

  • @rahulk8537
    @rahulk8537 2 роки тому

    as clean as a whistle!!

  • @kilaposhi
    @kilaposhi Рік тому

    You're the best C++ teacher I've found in my life!

  • @parikshit804
    @parikshit804 5 років тому

    never seen this detail anywhere. sweet.

  • @greob
    @greob 6 років тому

    I love optimizations, nice! :)

  • @p9malino267
    @p9malino267 5 років тому

    Your videos are gold!

  • @alfredli4032
    @alfredli4032 2 роки тому

    clear as crystal

  • @Haryyyy
    @Haryyyy 6 років тому +1

    Great! Thanks!

  • @bluehornet6752
    @bluehornet6752 Рік тому

    This is gold.

  • @SuperCacazinho
    @SuperCacazinho 3 роки тому

    bro... that's PURE *GOLD*

  • @rameynoodles152
    @rameynoodles152 5 років тому

    Wow, I had no idea that it worked like this!

  • @RoaiDude1
    @RoaiDude1 6 років тому

    Wow.. please make more of this kind of optimization videos and I'll make sure that whole of my class in tel aviv university computer science course will be happy to subscribe to your channel!!
    Im talking about the std:vector video ofc!

  • @struggleprogramming
    @struggleprogramming 3 роки тому

    Outstanding

  • @kylefan8478
    @kylefan8478 3 роки тому +1

    this is better than my uni programming course by far.

  • @Fr3akyPL
    @Fr3akyPL 6 років тому

    simple and great example!

  • @dariamagiera8685
    @dariamagiera8685 5 років тому +54

    your hair is goals 😂

  • @jcpartri
    @jcpartri 4 роки тому

    superb!

  • @eyalpery8470
    @eyalpery8470 4 роки тому

    Thanks!!

  • @Mooncake69420
    @Mooncake69420 5 років тому +1

    that guitar is going to topple anytime now

  • @shavais33
    @shavais33 3 роки тому

    I like the speed of these talks. I put them in the background and set the speed to about 1.5 or 1.25, but once in a while when it gets to something that causes a double take or that I want to pay specific attention to, I'll back it up a short bit and set the speed to normal. So for people who aren't already familiar, I bet it's about the right speed.

  • @ericjovenitti6747
    @ericjovenitti6747 2 роки тому

    Dude I don’t know why but read countless books but I learned so much more from how you explain things great job

  • @johetajava
    @johetajava Рік тому +6

    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.)

  • @ruslanmanikatov2238
    @ruslanmanikatov2238 3 роки тому

    thenks

  • @yoninonasade
    @yoninonasade 3 роки тому

    that's was a good episode.

  • @devprakash5320
    @devprakash5320 4 роки тому

    I didn't want to wink even once , but i had to . Thanks man , thanks for this wonderful content

  • @TheFreeSpiritKID
    @TheFreeSpiritKID 5 років тому

    Thx!

  • @chainonsmanquants1630
    @chainonsmanquants1630 3 роки тому

    Thanks

  • @shpack612
    @shpack612 2 роки тому

    ty good man

  • @mohammednihad6755
    @mohammednihad6755 6 років тому +1

    Optimization

  • @nissimhadar
    @nissimhadar 5 років тому +11

    This is the best explanation I have seen! I have also realized that watching videos teaches (me) much better than books.

    • @klarnorbert
      @klarnorbert 4 роки тому +3

      One of the reason I don't like Bjarne Stroustrup's books, because it's like he's talking an alien language.

  • @azulplus_
    @azulplus_ 6 років тому

    Hello, nice videos on your channel, what´s are the tools that you use to indicate the elapsed time in line, or is your IDE or any plug-in ?? I use Eclipse for c++, can you recommend any tool for optimize the code ?? Thanks

  • @yuezhao5799
    @yuezhao5799 5 років тому +3

    This is by far the best video I've ever seen

  • @manishgurawalia7625
    @manishgurawalia7625 3 роки тому +1

    I love C/C++ , they r just mindblowing

  • @AvelinoBego
    @AvelinoBego 6 років тому

    Great!

  • @chieeyeoh6204
    @chieeyeoh6204 Рік тому

    Cool!

  • @casvanmarcel
    @casvanmarcel 6 років тому

    optimising like a boss

  • @cipherxen2
    @cipherxen2 5 років тому

    I'm emplaced with this c++ series.

  • @NoName-tn8rq
    @NoName-tn8rq 5 років тому

    That's fucking amazing.

  • @afterlife1578
    @afterlife1578 3 місяці тому

    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

  • @mathieuguigue6086
    @mathieuguigue6086 5 років тому

    If I could like this video more than once, I would!!

  • @Mitchinator1
    @Mitchinator1 6 років тому +2

    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 3 роки тому

      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 2 роки тому +1

      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 2 роки тому

      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.

  • @multivalfran
    @multivalfran 2 місяці тому

    ily cherno

  •  Місяць тому

    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).

  • @Dr.tech-
    @Dr.tech- 3 роки тому

    thank you. That saved for me an very important ms. speed up 2x

  • @Erebus2075
    @Erebus2075 4 роки тому

    awesome^^

  • @visuallization
    @visuallization 2 роки тому

    Such a great video!! So why shouldn't I use emplace all the time?

  • @krentwhite2668
    @krentwhite2668 2 роки тому

    I've using vectors for 1 year without knowing this, Thanks Cherno

  • @teacup3000
    @teacup3000 6 років тому +4

    So is emplace_back now always the better option to push_back?

  • @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)

  • @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!!

  • @carlosgarciavigoa7937
    @carlosgarciavigoa7937 5 років тому +39

    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

  • @Traiden_
    @Traiden_ Рік тому +1

    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!

  • @tomsku69
    @tomsku69 5 років тому +2

    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

  • @hsyn-yldz
    @hsyn-yldz Рік тому

    My favorite part of this guy's videos : ) (9:26)

  • @haru02w89
    @haru02w89 10 місяців тому

    My main reason to learn C/CPP is actually be able to control that precisely what I want my computer to do

  • @amrob1768
    @amrob1768 3 роки тому

    you blew my mind in a way i felt like i'm a nerd

  • @paherbst524
    @paherbst524 4 роки тому

    Super useful. I'm impressed with your grasp and ability to teach

  • @PulkitMalhotra
    @PulkitMalhotra 3 роки тому

    c pillow like channel logo impressing

  • @aayushanand8285
    @aayushanand8285 2 роки тому +1

    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.

  • @mohdharis131
    @mohdharis131 5 років тому +6

    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 років тому +1

      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.

  • @ashutoshrautela3454
    @ashutoshrautela3454 6 років тому +5

    Please make an episode on templates as well

  • @A-_AkramahFaizi
    @A-_AkramahFaizi Рік тому

    what happens to the vertex made in the stack in the push_back method?
    Is it deleted after the push_back or does it remain in the stack?

  • @anonymoussloth6687
    @anonymoussloth6687 2 роки тому +1

    When we use emplace_back, does the vector object get constructed in heap?

  • @ZihadJoy
    @ZihadJoy 4 місяці тому

    "a professional knows what he is doing"