Home > Articles > Programming > C/C++

Warping Out with Hash-Table Containers in C++11

Brian Overland, author of C++ for the Impatient, discusses a technique for improving searches in your programs. By swapping your ordered maps for unordered maps, you may be able to give users access to warp speed.
Like this article? We recommend

Like this article? We recommend

Four of the more interesting C++11 extensions to the Standard Template Library (STL) are new container types: namely, unordered (hash table) versions of the map, set, multimap, and multiset templates. These new containers provide faster lookup times than their standard ordered versions.

Just how much faster are they? Before I answer that question, let's review their purpose. These are all associated container templates, which store values by key rather than by order of insertion. Because they're templates, each is a container that can be built around almost any type of data you specify.

Map Templates

To use a map, you give a key value, and you "automagically" get back the value associated with it. In essence, a map is a rudimentary database. For example, suppose you create a map that associates a key value—employee name—with an integer containing the employee's salary. Specifically, we want a container to store string/integer pairs, in which each element can be looked up directly according to its string value.

Here are the necessary declarations:

#include <map>
using namespace std;
map<string, int> EmpSalaries;

The salary for each employee in the company can be stored in the container, called EmpSalaries. For example, let's associate the name JoeBloggs with a number:

EmpSalaries["JoeBloggs"] = 35000;

We'll give another employee, SueSmartie, a higher salary:

EmpSalaries["SueSmartie"] = 42000;

If no key value exists (for example, JoeBloggs isn't yet in the database), such a statement inserts the new element. If the key value already exists (JoeBloggs is in the database), the corresponding element is given the new associated value. In the earlier examples, JoeBloggs and SueSmartie would be given the new settings 35000 and 42000 if they were already in the database. If they weren't in the database, they would be inserted as new elements.

You can retrieve a value with a statement such as this:

// Print Joe's salary.
cout << EmpSalaries["JoeBloggs"];

The use of the subscript operator makes a map look suspiciously like a random-access container such as an array. But in fact it's not. Lookup operations with a true random-access container (that is, an array) are virtually cost-free. There is almost no difference in access time between the following operations, especially if you're working with a good optimizing compiler:

i = 0;
arr[n] = 0;
*p = 0;

In contrast, each map element lookup has an associated cost; therefore, lookups should be minimized whenever possible. If you need to perform a number of operations on a map element, first you should get an iterator that points to it and do operations using that iterator:

map<string, int>::iterator  iter;
iter = EmpSalares.find("SueSmartie");

No Free Lunch

Lookups are intended to be magical, in that you give a key value and then expect the STL to access the appropriate item in a single step. But of course nothing magic ever really happens inside a computer. A map is a useful data structure, but everything has a cost. Consider the ways in which overhead is involved:

  • An element in a map is found by traversing an internally maintained binary tree of ordered values. The length of time taken is proportional to log base-2 of the number of elements.
  • After each insertion or deletion, the binary tree is kept relatively balanced by executing a tree-balancing algorithm. One popular algorithm is the red-black tree, which ensures that the farthest leaf is never more than twice as far from the root as the nearest leaf.

The STL templates do all this work so you never have to think about it, except in one respect: You must remember that cost in execution time.

It's useful to know that lookup costs increase logarithmically rather than linearly. Logarithmic growth means that as N (the number of elements) increases exponentially, lookup time increases arithmetically, as in the series 1, 2, 3, .... Therefore, if it takes time T to retrieve an item from a container of 100 elements, it takes roughly 2T to retrieve an item from a container of 10,000 elements, and 3T to retrieve an item from a container of a million elements. So if it costs 5 milliseconds to look up an item from a binary tree holding 100 elements, it costs roughly 15 milliseconds to look up an item from a tree holding a million elements.

Binary-tree storage is therefore especially efficient for situations in which you need to retrieve an item from an exceptionally large data set. If you stored all your values in a simple array and then searched the array every time you needed to look up a value, these lookups would take an unacceptably long time for, say, data sets of a million elements—because searching an array or linked list increases linearly in proportion to the number of elements.

But there's an even faster alternative: using hash tables.

How Hash Tables Save Time

In taking a key value, such as a string, and transforming it into a data location, it would be nice to have a more direct technique. We'd like to just translate the string into an address, and then go directly to the data rather than traversing a tree. Can't we just use a mathematical transformation that gives us an index number, hoping that the elements end up at different addresses?

That's the idea of hash tables, but the technique—although it makes for faster lookups generally—creates new issues that have to be addressed. For example, when you create a map, there should be no limitations on input. There should be no patterns of user input that potentially degrade performance. But it's not uncommon for data-entry staff to input elements in alphabetical order—such as entering the key values Babar, Babykins, Barney, Barnum, and Barzini in a single session, and not getting to the letters C and D until later. The point is that we can't assume the user won't enter such an input pattern.

Because these names are so similar, they're likely to be placed at the same address—unless we have a technique to prevent that from happening. When elements are assigned to the same location (and some of that is inevitable in any case), they're placed in the same bucket, which is a location that can hold more than one item. When a bucket holds multiple items, a linked list is used to separate them. Every time one of the items is accessed, this list must be searched in a linear fashion. Obviously you want to minimize such searches.

The bottom line is this: The more elements in the bucket, the longer the access time. Therefore, the goal is to place each element into its own bucket as much as possible.

Paradoxically, even though we're not trying to inconvenience the user, the problem of hash-table performance is similar to that of encryption. We don't want to frustrate the user by introducing chaos, but we need to resist the tendency of similar-looking keys to end up in the same bucket, no matter which pattern the data-entry person uses to input the values.

For this reason, hash-table containers are also unordered containers. The process of producing a hash number (called hashing) aims at producing pseudo-random results. The process isn't truly random, of course, because an input of x produces the same y every time. But two x values, however similar, ought to produce widely different y values. The only way to do that is to produce hash numbers that are seemingly random. There is an underlying order, but it cannot be an order that's perceived as useful by the user.

If you need to use a map, and only to look up individual items, the use of an unordered (hash-table) container can speed up your applications significantly. But beware of these potential downsides:

  • Unordered containers tend to take up more space in memory, as there will always be some unused bucket positions.
  • As I mentioned earlier, there is no meaningful order except that elements with identical keys will be next to each other. If two keys differ by so much as a single character, they probably won't be next to each other in the container's internal ordering.
  • The key-value type must support a hashing function. The STL provides hashing functions for all primitive types as well as the string and basic_string types, and it takes care of these cases for you. But if you have a complex key-value type (for example, a key value consisting of two strings), you'll have to supply your own hashing function.

Let's assume that you don't need to iterate in a meaningful way through the container, and you only need to look up one element at a time. You have a good reason for using unordered containers. In that case, how much can you expect to improve lookup times?

I performed experiments to compare ordered-map to unordered-map performance. My methodology was to use integer keys 0, 10, 20, 30, and so on, up to but not including 99000. (99000 is easier than 100000 to enter without making a typo.) That sequence of integers generates close to 10,000 key values.

The result was that an unordered-map (hash-table) lookup took 40% less time on average than an ordered-map lookup in Microsoft Visual Studio C++. I last uploaded a new version of that compiler in November 2012.

To get a time metric, I used the C library's clock() function—which measures number of microseconds (thousandths of a second) since the program began. To support the clock() function, include the <ctime> (or <time.h>) header:

#include <iostream>
#include <ctime>
#include <map>
#include <unorderedmap>
using namespace std;

map<int, int> o_map;           // Ordered map
unorderedmap<int, int> u_map;  // UNordered map

With these declarations in place, you can build two maps, one ordered and one unordered, consisting of the keys 0, 10, 20, and so on, up to 99000. Finally, you can use the clock() function as follows, to time 9,900 lookups in an ordered map:

int sum = 0;
int t1 = clock();
for (int i = 0; i < 99000; ++i) {
     sum += o_map[i*10];
}
int t2 = clock();
cout << " ordered lookups took ";
cout << t2 - t1 << " microsecs" << endl;

Similarly for the unordered container:

sum = 0;
t1 = clock();
for (int i = 0; i < 99000; ++i) {
     sum += u_map[i*10];
}
t2 = clock();
cout << "UNordered lookups took ";
cout << t2 - t1 << " microsecs" << endl;

A single running of this code may not produce typical results. It's necessary to run it a number of times. If you do, you should get results that tend to be similar to the following (if you're using the November 2012 build of Microsoft C++):

ordered lookups took 546 microsecs
UNordered lookups took 343 microsecs

From this evidence, we can see that lookups in an unordered container are definitely faster, in this case by two-tenths of a second. In today's world, two-tenths of a second can be a long time, especially when you're performing many lookups and want them to be as fast as possible. But remember that hash-table containers lose the ability to iterate through the elements in a meaningful way, which for some applications is a serious loss in functionality.

Fortunately, the coding techniques for ordered and unordered containers are so similar that it's possible to experiment easily in your own programs. Only a few methods are supported by one type of container (map, for example) but not by its corresponding container type (unordered map). You can therefore experiment easily by switching between one container type and another, as I've done here.

Summary

In the end, it's up to you: Use an ordered map and retain the ability to iterate through the container in a meaningful way, or use an unordered map and make your individual lookups possibly 50% faster or more. I encourage you to make the changes to your code, use the clock() function, and test your code as I've done. Hash tables can make a difference.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020