Efficient Use of STL

Source: Internet
Author: User

Efficient Use of STL

is only a choice of the problem, are STL, may be written out of the efficiency of several times;
Familiar with the following terms, efficient use of STL;

When the object is large, create a container of pointers instead of objects

1) STL works on a copy-based approach, and any elements that need to be placed in the STL will be copied;
It is also understood that the container of STL work is a new space opened in the heap, and our own variables are generally stored in the function stack or another heap space, in order to be able to fully control the STL's own elements, in order to be able to work in their own site, which involves replication;
If the replicated objects are large, the performance cost of replication is not small;
For large object operations, the use of pointers in place of objects can eliminate this cost;
2) only refers to the pointer copy operation, no additional class of constructors and assignment constructor calls;

vecttor <BigObj> vt1;vt1.push_bach(myBigObj);vecttor <BigObj* > vt2;vt2.push_bach(new BigObj());

Precautions:
1) The container must destroy the object pointed by the pointer before destroying it, otherwise it will cause the memory leak;
2) When using algorithms such as sorting, it is necessary to construct an object-based comparison function, and if the default comparison function is used, the result is based on the comparison of the pointer size, not the object;

Use empty () instead of size () to check if it is empty

Because for List,size (), each element is traversed to determine size, time complexity O (n), linear time, and empty always guarantees constant time;

Try to use interval member function instead of single element operation

Using interval member functions has the following benefits:
1) Fewer function calls
2) fewer elements to move
3) Less memory allocation

Example: Assigning the elements of the second half of the V2 to V1:
Cell-type operation:

for (vector<Widget>::const_iterator ci = v2.begin() + v2.size() / 2;ci != v2.end();++ci)v1.push_back(*ci)

Use the interval member function assign ():

Use Reserver to avoid unnecessary memory allocations (for vectors)

When the new element space is not enough, the vector will do the following:
1) allocate twice times the space of the current space;
2) Copy the current element into the new space;
3) before releasing the space;
4) Put the new value in the new space to specify the location;

Pre-allocated space avoids the cost of reallocating space and replication if the space is known in advance;
Note: reserve () only modifies the capacity, not the size, the addition of elements to the vector or the need to join through push_back;

Use ordered vectors instead of associative containers (phased operations apply)

Definition of the phased operation:
First do a series of inserts, completed, follow-up operations are queries;

In the phased operation, the use of vectors has the following advantages:
1) because the vector is orderly, the ordered advantages brought by the associated container are lost;
2) The query algorithm accesses the contiguous memory space faster than the discrete space under the premise that the binary method is used to find it;

Select carefully in the Insert () and operator[] of the map

Insert is efficient when inserting, because operator will first explore the existence of this element, and if it does not exist, construct a temporary one, then the assignment, and the construction of a temporary object;
When updating, [] more efficient, insert creates an object and then overwrites an existing object, whereas [] is a direct assignment on the original object;

The default comparison function for hash functions is equal_to, because there is no need to keep order;

Try to replace handwritten loops with algorithms

1) efficiency compared to handwriting higher;
STL code is written by C + + experts, the code written by experts is difficult to surpass in efficiency;
Unless we give up certain features to meet specific needs, it may be faster than STL, for example, to give up generality and portability based on programming on specific occasions;
2) not prone to error;
3) Programming with high-level thinking
Compared to the Assembly, C is a high-level language, a C-language statement, with sinks to write several needs;
Similarly, in the STL world, we also have high-level terminology:
High-level terminology: Insert/find/for_each (STL algorithm)
Low-level vocabulary: for/while (c + + syntax)
It's easier to think about programming in high-level terms;

Try to replace the same name algorithm with the member function

1) Based on efficiency considerations, the member function knows what unique properties the container and other containers have, and can take advantage of these features, while the general algorithm cannot;
2) for associative containers, the member function find is based on equivalence search, while the general algorithm find is based on equality to search; may result in different results;

Use function object instead of bare function as input parameter of algorithm

Because inline, in the way of a function object, inline is valid, and as a function pointer, the general compiler does not inline function pointers to functions, even if inline is specified;
Like what:

inline bool doubleGreater(double d1, double d2){    return dl > d2;}vector<double> v;...sort(v.begin(), v.end(), doubleGreater);

This call does not really pass the doublegreater to sort, it passes a doublegreater pointer.
A better way is to use a function object:

sort(v.begin(), v.end(), greater<double>())

Note: "Effcient C + +" in the experimental conclusion, the use of function objects are generally 1.5 times times the bare function, up to twice times more quickly

Choosing the right sorting algorithm

To think about our necessary needs before ordering, maybe we just need the first number of elements, and then we do not need to use the sort linear time tool, the performance consumes less parttition may be the better choice;
The efficiency of the following algorithms is decremented from left to right:

partition > stable_partition / nth_element / patical_sort / sort / stable_sort

Function Description:
Partition: Separates the set into satisfying and not satisfying a standard of two intervals;
Stable version of Stable_partition:partition;
Nth_element: Gets the first n elements in any order;
Patical_sort: Gets the first n elements, the n elements are sorted;
Sort: Sorts the entire interval;
Stable version of Stable_sort:sort;

Choosing the right Container

Why does vector not provide a push_front () member method? Because the efficiency is too poor, if there are too many requirements from the front inserted, you should not use the vector, and list;
Care about the search speed, first of all should consider the hash container (non-standard STL container, such as: Unordered_map,unordered_set), followed by the sort of vector, then the standard associative container;

Reference

"Effictive STL"
"Efficient C + +"

Posted by: Big CC | 23jun,2015
Blog: blog.me115.com [Subscribe]
Weibo: Sina Weibo

Efficient use of STL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.