Link to home
Start Free TrialLog in
Avatar of dearCode
dearCode

asked on

.add() method

I'm confused about which of these data structure has the fastest run time when adding.
1) ArrayList
2) LinkedList
and how can I prove it. Thank you
Avatar of Jose Parrot
Jose Parrot
Flag of Brazil image

By definition, in an array list the elements are disposed in sequence, say
ARRAYLIST : value, value, value,....
Ex: LIST A = {10,20,30,40,50} is the same as A[0]=10, A[1]=20, ...
such that a pointer, pointing to element A[0], when incremented, will point to element A[1].

By the other hand, a Linked List has another structure, say
LINKLIST : (value, pointer to next element), (value, pointer), (value, pointer),...
Ex: LIST B = { (5,2), (3,-1), (10,1) }
say, first element has value = 5, next is the one with index 2, which has value = 10, and follows the element with index 1, which value = 3. This is the last element, because has an index -1. (Please, note, this is an exemple, not all LINKED list use -1 as terminator nor has ever the described structure).

It is easy to cloclude that an ARRAY LIST is faster than a LINKED one when we need to retrieve a value. The advantage of LINKED lists is that we can arrange them such that they use less memory, if they represents a hash, for example. It is the case of an array from 0 to 1000 which never will use the range 200 to 800. An ARRAY will spend memory to store 1000 eleements and a LINKED list will spend memory to store 400 elements and 400 indexes, which would be smaller than the entire ARRAY list.

To store data the difference is still bigger. In an ARRAY you know where is the element 529: it is in the cell A[529], so you can store data immediatly. In a LINKED list, you should walk element by element until to reach element 525, because you don't know where it is, in advance.

Jose
Avatar of CoruNethron
CoruNethron

You can check what code is faster with this template:'

using System.Diagnostics;
...
Stopwatch sw = new Stopwatch();
sw.Start();
//--Your first code here--
sw.Stop();
//--Trace sw.ElapsedMilliseconds to your output
sw.Reset();
sw.Start();
//--Your second code here--
sw.Stop();
//--Trace sw.ElapsedMilliseconds to your output

Now just choose where sw.ElapsedMilliseconds is smaller.
Sorry for my english.
ASKER CERTIFIED SOLUTION
Avatar of Member_2_5069294
Member_2_5069294

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Actually, when I say the array is faster when adding to the end, I don't include any overhead for copying data to the end of the list.  That depends on size of the item and the specific behaviour of the program.