Hassan Jalil
Hassan Jalil

Reputation: 1194

std::pair vs Array

I am creating a Map with key and value. The values have to have two separate entries. Now the first two options that come to my mind is
either go with

Map< int,array[2] > 

or

Map < int,pair < float,float > >  

Which one of these two is better when it comes to memory and execution time. I personally think array would be better since we do not need to perform any search functions. I just plan to access the location using subscript and changing them.

Upvotes: 8

Views: 6559

Answers (3)

george
george

Reputation: 1829

To answer the initial question:

Compiler is smart enough that both std::pair and an array with 2 elements are exactly the same thing and it will give you the same assembly code. So you will not see any performance difference.

To give you an example:

the following code:

#include<utility>
int square(int num) {
    int arr[2] = {0, 1}; 
    std::pair<int, int> p = {0, 1}; 
    return num * num;
}

will be converted to:

square(int):
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-20], edi
        mov     DWORD PTR [rbp-8], 0  // arr[0]
        mov     DWORD PTR [rbp-4], 1  // arr[1]
        mov     QWORD PTR [rbp-16], 0  // p[0]
        mov     DWORD PTR [rbp-12], 1  // p[1]
        mov     eax, DWORD PTR [rbp-20]
        imul    eax, eax
        pop     rbp
        ret

to convert your C/C++ code to assembly you can use this website: https://godbolt.org/

Upvotes: 3

rubenvb
rubenvb

Reputation: 76519

You have three choices, and the right one depends on what the two int represent.

  1. using mymap = std::map<int, std::array<float, 2>>;
  2. using mymap = std::map<int, std::pair<float, float>>;
  3. The preferred option for readable code using this construct:

    struct somethingmeaningful { float meaningful1; float meaningful2; };
    using mymeaningfulmap = std::map<int, somethingmeaninful>;
    

Note how the final one magically became meaningful ;-).

Also, notice how I completely disregarded your question about which is faster. The reason for this is that it doesn't matter. Readable code with meaningful names is always more performant in the long run!

Upvotes: 8

dirkster
dirkster

Reputation: 522

To get the obvious out of the way, the first example should probably be

std::map<int, std::array<float, 2> >

But it's not quite clear what you mean by

[...] plan to access the location using subscript [...]

Note that for a pair, you would do something like

std::pair<float, float> a;
a.first = 1.0;

while for an array the syntax would look like that

std::array<float, 2> a;
a[0] = 1.0;

Then an array probably has more overhead, since it provides other functionality like iterators etc. which you won't make use of. The best way is always doing some experimentation. I find that keeping my implementations open for swapping containers and so on also helps me to keep the code clean and modular.

Upvotes: 6

Related Questions