为什么数组列表动态增加而不动态减少 [英] Why Array list increase dynamically and not decrease dynamically

查看:81
本文介绍了为什么数组列表动态增加而不动态减少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的疑问,当Arraylist变满时,它会以21.5或old_capacity * 3/2 +1或其他倍数增加其大小,并在其中添加新元素。然后,如果数字被某种因素删除,为什么不动态减小它的大小。就像我在arraylist中有10000个元素,并且在特定时间删除所有元素一样,现在数组列表中只有100个元素。它仍然保存10000个对象内存。为什么我必须调用trimTosize()之类的东西?为什么不是他们自动?我错过了什么 .. ?请不要告诉我该怎么做,我想知道为什么我们必须这样做?
谢谢

I have a simple doubt , Arraylist increase its size with factor ( 2,1.5 or old_capacity*3/2 +1 or what ever) as it got full , and add new element in it. Then why dont it decrease it size dynamically if number is removed by some factor. Like if I have 10000 element in arraylist and at particular time all the elements are removed , only 100 elements are their in array list now It still hold 10000 object memory. Why i have to call trimTosize() or something? why it is not their automatically? Did I miss something .. ? Please dont tell me how to do it, I want to know why we have to do it ?? Thanks

推荐答案


然后,如果不删除数字,为什么不动态减小其大小
一些因素。

Then why dont it decrease it size dynamically if number is removed by some factor.

出于性能的原因。分配内存始终是一项昂贵的操作。不取消分配它的逻辑是,如果您的数据结构达到了给定的大小,即使您删除了元素,将来它也可能会再次达到该大小。

For performance reasons. Allocating memory is always an expensive operation. The logic behind not deallocating it, is that if your data structure has reached a given size, even if you remove elements, then it will probably reach that size again in the future.

取消分配也可能也很昂贵(这取决于实现方式,但这通常是正确的。请参见 realloc

Deallocating maybe also expensive too(this depends on the implementation but it's generally true. See realloc for C), because you may need to release the whole chunck of previously allocated memory, and then reallocate a new chunck for the resized structure.

这篇关于为什么数组列表动态增加而不动态减少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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