"的std ::分配器"或关键字“new”实现容器时 [英] "std::allocator" or keyword "new" when implementing a container

查看:89
本文介绍了"的std ::分配器"或关键字“new”实现容器时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我即将实现一个双向链表(默认的std :: list不适合我的需要,因为我需要直接访问内部节点)。我的问题是,在实现它时是否应该使用std :: allocator或关键字new。我理解分配器的功能,但我不打算制作任何自定义分配器,所以在性能上使用新会有什么不同吗?



所以要澄清,使用std :: allocator或new之间是否有任何性能差异。

I am about to implement a doubly-linked list (the default std::list doesn''t fit my needs because I need direct access to the internal nodes). My question is if I should use "std::allocator" or the keyword "new" when implementing it. I understand the power with "allocator" but I don''t plan to make any custom allocator, so will it be any different against using "new" in performance?

So to clarify, is there any performance difference between using "std::allocator" or "new".

推荐答案

这完全取决于你。此功能用于为用户提供分配方法的访问权限,以提供备用分配器。在使用容器的代码中,它可以是子分配器或其他东西,用于提高性能,考虑分配/释放的特定顺序,数据量等。例如,更快的子分配器技术可以改进性能是容器元素分配少量内存。



这一切都取决于你的目的。通常,如果要为潜在用户的广泛受众发布类,则需要引入自定义分配器。如果您针对更多特殊情况执行此操作,对于您自己的情况,您可能非常清楚,您可能希望跳过此功能。在这种情况下,毕竟,当您面临需要使用自定义分配/释放来优化集合的使用时,您可以在以后改进实施。



我必须注意到,链接列表或树等所有结构都依赖于频繁使用分配/释放,相比之下,依赖于基于数组的容器(更确切地说,更大的连续内存块)。这种结构本质上固有地造成了高水平的记忆碎片;项目/节点分配的内存可以自由地与堆上其他不相关的对象交织。这就是为什么自定义分配对于这样的数据结构更重要的原因。


-SA
It''s totally up to you. This feature is used to give the user access to allocation method, to provide an alternative allocator. In the code using the container, it could be a sub-allocator or something, used to boost performance, taking into account the particular order of allocation/deallocation, amount of data, etc. For example, a faster sub-allocator technique could improve performance is the container elements allocate tiny amount of memory.

It all depends on your purpose. Generally, if you want to publish you class for a wide audience of the potential users, you would need to introduce custom allocator. If you do it for more special cases, for your own cases you know pretty well, you may want to skip this feature. In this case, after all, you can improve your implementation later, when you face with the need to optimize the use of your collection by using custom allocation/deallocation.

I must note that all structures like linked lists or trees rely on very frequent use of allocation/deallocation, in contrast, say, to containers based on array (more exactly, on bigger continuous chunks of memory). Such structures, by their nature, inherently create high level of fragmentation of memory; the memory allocated by items/nodes can freely interlace with other unrelated object on the heap. That''s why custom allocation is more important for such data structures.

—SA


这篇关于"的std ::分配器"或关键字“new”实现容器时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆