JAVA Programming : Why there is performance issue in Collection.
JAVA Programming
Why there is performance issue in Collection !
- Why do we need Arrays: To store the homogeneous objects with a single reference, we use Arrays in our daily programming practice, e.g. Students [] S=new Students[100], however we can also store heterogeneous objects in Arrays using Object [] obj= new Object [100].
- Array's are fixed in size, Array concept was not made on any underlying Data Structure, because of that, we don't have any methods associated with it, to perform operation we have to write the code explicitly, hence the complexity of code increases with increasing module,
To overcome this problem the Collections came in picture, which has many features like:
- Support Homogeneous and Heterogeneous object both.
- Collections has their ready made methods , no need to write the code explicitly.
- Collections are based on re sizeable arrays where they can expand automatically, if needed.
Let's see how they expand automatically.
- We create a collection of size 10. [0,1,2,3,4,5,6,7,8,9]
- Now we have entered the data till last position, for the new entry collection will grow automatically.
Formulae on which the Collection expansion take place:
New Collection Size= (Old Collection Size*3/2) +1;
considering the last example:
Old size = 10,
now new size will be:
New Size =(10*3/2)+1; -----> 16,
hence while inserting the 11th
element in collection the size of collection will be 16. Next time while
entering the 17th element the collection size would be
New size=(16*3/2)+1; ----->25.
Performance(Arrays Vs. Collection):
As we have seen the collection provide more features in comparison to
that of Arrays, hence obviously the performance of collections would be
better than Arrays, however this is totally opposite in practical
scenario.
Why the performance of collection in poor as when comparing to Arrays:
We have seen that Collection is grow-able in size , but this feature
only make it poor in performance case, when we compare it with Arrays,
Lets understand it with a simple example;
Let's have an Arrays of size 10.
Let's have a sample collection of size 10.
Now since Collection is Grow-able in nature, we can add 11th element in this above example,
Why this performance issue?:To work over this we have to go in depth of the working of collections, let's see how it works:
- When we enter a new entry in the collection which is beyond the limit, the collection grow in size(based on the formula we discussed above) and an EMPTY collection of new size is generated.Here in above example when we tried to entered the 11th element the new empty collections gets generated.
- Now the elements of previous collection start copying to the new collection of new size,
- As this copying process done, the reference of old collection gets shifted to new one, in this way we get our new collection with 11th element.
Smiles !
Comments
Post a Comment