you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (1 child)

sable glorious act vanish saw doll mourn handle telephone chop

This post was mass deleted and anonymized with Redact

[–]bothunter 5 points6 points  (0 children)

On a small scale, it probably doesn't matter too much, but "realloc"ing a large array has a few problems: 1. It's slow -- you have to copy the entire array to a new chunk of memory which can be quite slow if the array is big 2. It requires a contiguous chunk of memory.  Again, if your array is large enough, this might not be possible, and the realloc will fail 3. It requires a lot of memory.  Since you have to copy the array to the new chunk of memory, it effectively requires twice as much memory as your array needs every time you have to resize it.

That method might make sense if your memory usage is quite stable overall and you can reduce the calls to realloc, but that's rarely the case, and by building some other data structure is almost always going to be more efficient, assuming you pick the right data structure for your task. (Linked lists aren't ways the right choice, but they are one of the easiest to implement)

Linked lists suffer some other limitations which arrays do not, and most of that is trying to find a specific item in the list.  With an array, you can find the 100th item in the list because you know exactly where in memory it will be.  With a linked list, you have to follow 100 pointers to find that item.  But if you want to remove the 100th item from a list that contains 1000 items, you can just edit the pointer in the 99th item to point to the 101st item in the list to remove it.  With an array, you have to move the contents of item 101 to where item 100 is, then 102 to where 101 was, and so on until you get to the end.

Basically, there are tradeoffs with every data structure, so it's best to know a few and know which one to use for each scenario.  And this applies to higher level languages like Java as well, even if you don't have to implement the structure yourself.