I am building a large queue of messages and using only PUSH and POP so which will be more efficient (vector or Queue) to maintain a large data with maximum speed
struct MQStruct {
wchar_t *serviceName;
int durability;
int msgType;
int msgHeader;
wchar_t *msgId;
wchar_t *payload;
int payloadSize;
int ttl;
int priority;
}MQStructObj;
vector<MQStruct> MQvector;
queue<MQStruct> MSQ;
int SendMessage(wchar_t *serviceName, int durability, int msgType, int msgHeader, wchar_t *msgId, wchar_t *payload, int payloadSize, int ttl, int priority) {
MQStructObj.serviceName=serviceName;
MQStructObj.durability=durability;
MQStructObj.msgType=msgType;
MQStructObj.msgHeader=msgHeader;
MQStructObj.msgId=msgId;
MQStructObj.payload=payload;
MQStructObj.payloadSize=payloadSize;
MQStructObj.ttl=ttl;
MQStructObj.priority=priority;
//Which one is better (Vector or Queue) in term of memory, speed and why
MSQ.push(MQStructObj);
//OR
MQvector.push_back(MQStructObj);
return 0;
}
Vector is efficient for random access (which has time complexity), but not for insertions and deletions (which have time complexity for each insertion/deletion). Queue is efficient when you want to add types from one side, and remove from the other. You won't have efficient random access nor insertion.
A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.
One main difference between vectors and deques is that the latter allows efficient insertion at the front of the structure as well as the back. Deques also do not guarantee that their elements are contiguous in memory so the at-style operator (indexing) may not be as efficient.
Queue is significantly faster than List , where memory accesses are 1 vs. n for List in this use case. I have a similar use case but I have hundreds of values and I will use Queue because it is an order of magnitude faster.
With std::vector
you can not efficiently simulate a queue - you may only PUSH and POP from one side of the container. If you need to implement a message queue then use a queue, that's what it's meant for.
There are many discussions regarding queue/vector/list on SO, you could search and reuse the resource. In short:
std::queue
: If you need fast insertion and deletion at both its beginning and
its end;std::vector
, if you need random access to elements std::list
As you use only push/pop to the container, std::queue
is the way instead of std::vector
for sure.
You can get more details from: http://en.cppreference.com/w/cpp/container
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With