Robin Rodricks
Robin Rodricks

Reputation: 113976

Which is preferable, a = [] or a = new Array()?

In Actionscript 3, which is preferable?

a = [1,2,3];

or

a = new Array(1,2,3);

It appears that calling the Array constructor with data as individual arguments would be slower and that the other method would be some sort of direct memory copy.

Do you know which is better to use in most cases, and why?

Upvotes: 6

Views: 1837

Answers (3)

Tim
Tim

Reputation: 56827

I prefer square brackets for almost all cases simply to avoid confusion.

The array constructor has 2 forms:

  • Array(...)
  • Array(size:int)

The first form creates and array with the listed parameters as values, and the second form creates an array with that number of elements. It's all good until you want to initialize an array with a single int:

  • new Array() => []
  • new Array("foo") => ["foo"]
  • new Array("foo", "bar") => ["foo", "bar"]
  • new Array(42,43) => [42,43]
  • new Array(42) => [undefined, ...undefined x 40..., undefined]

That inconsistency bit me a couple times before I just stopped using the Array constructor, except for the extremely rare occasion when I want an array with N undefined elements.

Upvotes: 7

Myk
Myk

Reputation: 6215

Using an Array Literal (var a:Array = []) is always going to be faster than saying new Array(), and I believe is considered to be a best practice.

Upvotes: 6

cdhowie
cdhowie

Reputation: 169018

I prefer the square brackets because it's a more concise and easy-to-read syntax.

The latter syntax will in fact be a bit slower, since you may replace the default array constructor by doing Array = function() { ... }; -- at least in most ECMAScript variants this works. So using that form will require the global Array function be looked up first.

Upvotes: 9

Related Questions