0

Would it be faster to use

var lastelement = myarray[myarray.length - 1];

or

var lastelement = myarray.reverse()[0];

and why?

7
  • 10
    Reversing an array just to get the last element ? Seriously ? BTW you probably forgot some parenthesis. Commented Dec 12, 2013 at 14:43
  • 7
    Note that instead of asking SO, you could test by yourself, for example using jsperf.com Commented Dec 12, 2013 at 14:44
  • micro optimization alert! Commented Dec 12, 2013 at 14:52
  • 1
    I think you meant myarray.reverse()[0]. Maybe it shows you better how the computation differs. Commented Dec 12, 2013 at 14:53
  • Which is faster, taking a card off the bottom of the deck, or reversing the order of the entire deck and then taking one off the top? Commented Dec 12, 2013 at 14:56

5 Answers 5

4

Just think about it.

If you know how long an array is, it is much faster to just get the last value than to have to compute the reverse!

Sign up to request clarification or add additional context in comments.

Comments

4

It is faster to access an element by its index, as it should have O(1) complexity. Reversing an array and then accessing the first index, on the other hand, would have at least O(n) complexity, depending on how the reversing algorithm is implemented.

3 Comments

Complexity isn't speed. Of course it's faster to query the length but that's not a proof.
edit: Well, in fact he asked for the fastest way. i'm sorry. Can i ask you why complexity doesnt mean speed btw?
@luizrogeriocn: Sometimes naive solutions with worse complexity are faster than more efficient algorithms for small inputs - and sometimes they still are for surprisingly large inputs.
2

I'll take this from a different angle than has been answered here. Chances are you just want to get the last element, you don't want to do anything to the actual array itself. If you use array.reverse to get the last element, you are actually changing the array (probably an unpleasant side effect in your case).

var myArray = [.....]; // some array
var lastElement = myArray.reverse()[0]; // get the last element
var firstElement = myArray[0]; // tricked you! This is now the same as
                               // lastElement because the myArray object
                               // in memory has been reversed.

So if you want to get the last element without changing the array you'd have to do this:

var myArray = [.....]; // some array
var lastElement = myArray.slice().reverse()[0]; // copy and get the last element
var firstElement = myArray[0]; // this is the correct first element

Pretty obvious which way is more efficient now.

3 Comments

Why does defining lastElement in terms of a reversed myArray change the definition of myArray itself? That's like saying var foo = 2 and then saying var bar = foo + 1 and expecting foo === 3 now. Am I missing something?
The reverse() method changes the array object itself, rather than simply returning a new, reversed array (it returns the same, mutated array), which can lead to unintended consequences. However your misunderstanding may have been a result of the way my answer was worded. To use your example, it would be like saying, var foo = 2,bar=foo++; Now bar === 3 and foo === 3
Oh, interesting. I didn't realize that methods like that would mutate the original var in memory. I thought they only affected the borrowed reference being used in the new definition. Good to bear in mind. Thanks!
1

Array.reverse() replacing old array with new reversed array in same reference ,crating the new array with new elements is much slower than get array element by index. var lastelement = myarray[myarray.length - 1]; Is much faster.

1 Comment

Please format your code to improve the readability of your answer.
0

The real efficient solution is to use a red and black binary tree (http://en.wikipedia.org/wiki/Red%E2%80%93black_tree ) where you'll store in each node one array value, the delta with the previous and next item, as well as the relative position to median. Then with only a few traversal you should be able to identify the last element (last element is the one having an index with biggest spread to median index, while having a previous item and no next item).

The trick is that each traversal takes only O(ln(n)) and since you do less than ln(n) traversal, time is below O(sq(ln(n))), so it's very fast.

Edit : following Bergi's constructive comments, i just wonder if it wouldn't be faster to just use arrays for this, by using a Fast fourier transform on an array containing all indexes of the array, then identifying last element with a frequency analysis, then convert back the array to get the number out of the frequency. I apologize if i'm unclear, i don't see clearly all steps at the time of writing, but i think it's a idea worth following.

3 Comments

We can assume that arrays (and vectors) have known length and constant lookup time, so that's much better than most tree implementations :-)
@Bergi : thanks, i'll have to dig into javascript specifications then. i edited.
Uh, it seems you have misunderstood the question. The OP just wants to access the "last" element in an array, not determine the biggest one or something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.