Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lists:append/2 versus erlang:'++' /2, appending to end of list Versus appending to its Head

Of the two given pairs of comparisons, Which one (of each pair) is more expensive to System Resources in Erlang:

Qn1: lists:append(L1,L2) versus erlang:'++'(L1,L2)
Qn2 Writing to the head of a list with say: [NewHead|List] versus writing to the end of the list with: List ++ [NewValue]

I have asked this because there is an intensive part of my program which will be reading and writing into lists. I need to decide wether i will be writing to the lists' heads or writing to their ends, or vice versa.

like image 952
Muzaaya Joshua Avatar asked Aug 30 '11 10:08

Muzaaya Joshua


People also ask

Which method is best to use when adding an item to the end of a list?

If we want to add an element at the end of a list, we should use append . It is faster and direct. If we want to add an element somewhere within a list, we should use insert . It is the only option for this.

Which is faster append or extend?

For large lists with one million elements, the runtime of the extend() method is 60% faster than the runtime of the append() method.

How do you append to the end of a list in Python?

Python's append() function inserts a single element into an existing list. The element will be added to the end of the old list rather than being returned to a new list. Adds its argument as a single element to the end of a list.


1 Answers

1: They are the same function. 'append' is an alias for '++' (or vice versa). See also Erlang ++ operator. Syntactic sugar, or separate operation?

2: Don't build a list incrementally by appending. Appending once is OK, but appending in a loop will give you quadratic behaviour. I.e., AddedStuff ++ Accumulator is OK (even in a loop), because you're growing "to the left", but Accumulator ++ AddedStuff in a loop (growing to the right) is really bad. It's much better to grow to the left and then reverse or sort afterwards if the order is important.

like image 51
RichardC Avatar answered Sep 27 '22 22:09

RichardC