C++ - Performance of vector of pointer to objects, vs performance of objects

后端 未结 3 977
别那么骄傲
别那么骄傲 2021-01-02 18:13

In this case the question scenario is a game, so all resources are allocated at the beginning then iterated over for a level.

The objects being stored in the vector

3条回答
  •  Happy的楠姐
    2021-01-02 18:55

    No, She is not wrong, she is absolutely right, though you are asking only about fast iteration, but that has alot of link with Memory... More the memory stack slower will be the access...

    I have a live demo...

    #include 
    #include 
    #include 
    #include "CHRTimer.h"
    
    struct Items
    {
        std::string name;
        int id;
        float value;
        float quantity;
    };
    
    void main()
    {
    
        std::vector vecItems1;
        for(int i = 0; i < 10000; i++)
        {
            Items newItem;
            newItem.name = "Testing";
            newItem.id = i + 1;
            newItem.value = 10.00;
            newItem.quantity = 1.00;
    
            vecItems1.push_back(newItem);
        }
    
        CHRTimer g_timer;
        g_timer.Reset();
        g_timer.Start();
        for(int i = 0; i < 10000; i++)
        {
            Items currentItem = vecItems1[i];
        }
        g_timer.Stop();
        float elapsedTime1 = g_timer.GetElapsedSeconds();
        std::cout << "Time Taken to load Info from Vector of 10000 Objects -> " << elapsedTime1 << std::endl;
    
        std::vector vecItems;
        for(int i = 0; i < 100000; i++)
        {
            Items *newItem = new Items();
            newItem->name = "Testing";
            newItem->id = i + 1;
            newItem->value = 10.00;
            newItem->quantity = 1.00;
    
            vecItems.push_back(newItem);
        }
    
        g_timer.Reset();
        g_timer.Start();
        for(int i = 0; i < 100000; i++)
        {
            Items *currentItem = vecItems[i];
        }
        g_timer.Stop();
        float elapsedTime = g_timer.GetElapsedSeconds();
        std::cout << "\nTime Taken to load Info from Vector of 100000 pointers of Objects -> " << elapsedTime;
    }
    

提交回复
热议问题