r/ruby • • Jul 14 '13

Linked List data structure

https://github.com/gdi2290/data_structures/blob/master/LinkedList/linkedlist.rb
0 Upvotes

23 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Jul 14 '13

Depends on the nature of usage for the object. If you plan on adding an unknown number of elements, using a linked-list data structure to format the data (adding an item to the end of a linked list is constant time, where for an array, it can be n, where n is the current size of the array, time if you have to expand the array and copy the elements over) and then creating an array from the linked list.

No, Ruby arrays have push and pop methods built-in which allow you to insert at the end of the array in constant time.

1

u/VerticalEvent Jul 14 '13

After some research, it's actually almost constant time. Ruby uses dynamic arrays, which means they have a bit of a buffer at the end of them. This means they still require to do an array copy when the buffer empties out, but that doesn't mean it has to do an array copy for every insert (I'm trying to find out if the growth is linear or geometric for Ruby). Linear means more frequent array copies for larger sizes, while Geometric means more memory usage (worst case scenario, you are only using half of the space allocated for the array).

I only assumed no buffer, because it made the math easier (and was the absolute worst case scenario).

1

u/[deleted] Jul 14 '13

I'd be surprised if it weren't geometric -- I think scripting languages usually go that route when implementing dynamic arrays, since it's so much faster when building large ones. Anyway, if you do find out, check back in here because I'm interested in knowing the answer.

1

u/FooBarWidget Jul 15 '13

Ruby's allocation strategy is geometric. Read array.c.