Thursday 24 November 2016

How array is giving better performance while retrieving element based on its index?

The answer is array stores all the element in the Contiguous Memory Allocation. Based on the base memory address (address of first element in the array),  array increase its pointer by adding the index which is passed.  For example: array[4] , index 4 will be added to the pointer and now pointer will be pointing fourth element of array.  Lets see the below explanation.

we all know that, array is a list of  element's of same data type. It can be primitive data type such as int, char, double, float or it can be user defined data type such as Objects.

we can access those elements based on the index(starts with 0 - first element). So each element in a array is sequentially associated with the index of the array.  For example:

     int a[] = {12,13,17,15,18,19}

    12 = index 0
    13 = index 1
    17 = index 2
    15 =    ...    3
    18 =    ...    4
    19 = index 5

  Array size is 6 

In JVM, there are different type of approach is followed while allocating memory based on the data type. Array is based on contiguous memory allocation(one of the oldest memory allocation scheme), memory is allocated sequentially for all the elements in array. Lets see how the memory allocation is done for the above array.

In java, int variable takes 4 byte as size, the above array need 24 bytes (size*4 bytes = 6*4 = 24 bytes) in memory.  The below image depicts the allocation in memory.



In the above chart, memory allocation starts from 1000 and allocating 4 bytes for each elements from the array. Base pointer always store the starting address of the array. While accessing, based on the index, array pointer will take summation of base pointer with (index * size of data type) to fetch the exact value of the array element.

For example:-
      int fourthElement = a[3];


The above code will have below logic in the system code.
            int array_pointer = (index*byte of int) + Base pointer
            int array_pointer = (3*4)+1000 = 1012 (Fourth element address).

The same logic is applicable for all the data types. Because of this logic, array doesn't traverse through all the elements  in the array.  

This implementation gives more performance while retrieving the element based on its index.




If you like the above solution . Please share this blog




              
  




   
   

     

No comments:

Post a Comment

s