首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用unordered_map的模板代码膨胀

使用unordered_map的模板代码膨胀
EN

Stack Overflow用户
提问于 2012-06-25 19:09:44
回答 2查看 840关注 0票数 17

我想知道unordered_map是否是使用类型擦除实现的,因为unordered_map<Key, A*>unordered_map<Key, B*>可以使用完全相同的代码(除了强制转换,这在机器代码中是无操作的)。也就是说,两者的实现都可以基于unordered_map<Key, void*>来节省代码大小。

更新:这种技术通常被称为Thin Template Idiom (感谢下面的评论者指出了这一点)。

更新2:我对Howard Hinnant的观点非常感兴趣,希望他能读到这篇文章。

所以我写了这个小测试:

#include <iostream>

#if BOOST
# include <boost/unordered_map.hpp>
  using boost::unordered_map;
#else
# include <unordered_map>
  using std::unordered_map;
#endif

struct A { A(int x) : x(x) {} int x; };
struct B { B(int x) : x(x) {} int x; };

int main()
{
#if SMALL
    unordered_map<std::string, void*> ma, mb;
#else
    unordered_map<std::string, A*> ma;
    unordered_map<std::string, B*> mb;
#endif

    ma["foo"] = new A(1);
    mb["bar"] = new B(2);

    std::cout << ((A*) ma["foo"])->x << std::endl;
    std::cout << ((B*) mb["bar"])->x << std::endl;

    // yes, it leaks.
}

并确定具有各种设置的编译输出的大小:

#!/bin/sh

for BOOST in 0 1 ; do
    for OPT in 2 3 s ; do
        for SMALL in 0 1 ; do
            clang++ -stdlib=libc++ -O${OPT} -DSMALL=${SMALL} -DBOOST=${BOOST} map_test.cpp -o map_test
            strip map_test
            SIZE=$(echo "scale=1;$(stat -f "%z" map_test)/1024" | bc)
            echo boost=$BOOST opt=$OPT small=$SMALL size=${SIZE}K
        done
    done
done

事实证明,在我尝试的所有设置中,unordered_map的许多内部代码似乎被实例化了两次:

With Clang and libc++:
          |   -O2   |   -O3   |   -Os
-DSMALL=0 |  24.7K  |  23.5K  |  28.2K
-DSMALL=1 |  17.9K  |  17.2K  |  19.8K


With Clang and Boost:
          |   -O2   |   -O3   |   -Os
-DSMALL=0 |  23.9K  |  23.9K  |  32.5K
-DSMALL=1 |  17.4K  |  17.4K  |  22.3K


With GCC and Boost:
          |   -O2   |   -O3   |   -Os
-DSMALL=0 |  21.8K  |  21.8K  |  35.5K
-DSMALL=1 |  16.4K  |  16.4K  |  26.2K

(使用Apple的Xcode的编译器)

现在来看问题:是否有一些令人信服的技术原因使实现者选择省略这个简单的优化?

还有:为什么-Os的效果与宣传的完全相反?

更新3

根据Nicol Bolas的建议,我用shared_ptr<void/A/B>而不是裸指针(用make_shared创建,用static_pointer_cast转换)重复了测量结果。结果中的趋势是相同的:

With Clang and libc++:
          |   -O2   |   -O3   |   -Os
-DSMALL=0 |  27.9K  |  26.7K  |  30.9K
-DSMALL=1 |  25.0K  |  20.3K  |  26.8K


With Clang and Boost:
          |   -O2   |   -O3   |   -Os
-DSMALL=0 |  35.3K  |  34.3K  |  43.1K
-DSMALL=1 |  27.8K  |  26.8K  |  32.6K
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11188204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档