For a project we have to optimize code to calculate a certain prime number. My question is in terms of time how much faster or slower is it to initialize a Linked list in comparison to an array. Obviously with smaller amounts of data it is negligible however we are working with 100,000,000 different data points so in this case it does make a difference.
Share
If you allocate ALL 100,000,000 points at once, array allocation is a single, constant time operation.
For linked lists, if you’re allocating ALL numbers at once, then your lookups will be prohibitively slow.
If optimizing for space : use the linked list, since it will never be any larger than necessary, and deletions can easily free up memory. If optimizing for time, the array will be faster for lookups.
If you have to choose quickly, then the array is probably the way to go. I’ve never seen a complex mathematical algorithm implemented in a linked list. Linked lists are usually just good for learning the fundamentals of memory, computation, and pointers — they don’t seem to have much algorithmic value.
Finally, with collection types, you might get the best of both worlds – the initial time will be small for initialization, but once the collection gets to a given size, there might be a moment where it has to reallocate some new memory.
Practically speaking
I rarely find that a linked list or arrays are all that necessary … Most jobs do alot better with a abstract collection type (i.e. a vector). But I am surmising that this is a homework assignment… Maybe consider adding that tag to the post ?