1

I have a case where a javascript array may be initialized repeatedly even when it has already been re-initialized. What I mean by initialize is this:

arr = [];

In most cases the array will already be empty so no need to perform this step. Is there any cost to doing this that would justify wrapping a condition around it?

if (arr.length > 0) { 
    arr = [];
}

I can also set a flag to indicate the state of the array but then I would need to maintain the state of this flag.

By the way, this is in an angular application and the function that contains this may be called repeatedly during the digest cycle. I may reconsider the overall approach but I am still curious if re-initializing an array when empty is essentially free.

user1843640
  • 3,613
  • 3
  • 31
  • 44

1 Answers1

1

You need to benchmark your code before you start optimizing. This may not be an issue at all and probably isn't, because you aren't re-initializing anything.

The arr = [] expression does nothing to the existing array (it does not empty it of items or modify it at all), it simply assigns an empty array to arr. Assignment is cheap.

Depending on your code and runtime (optimizer), the [] expression may need to allocate a new empty array every time. That will be more expensive than assignment, but is not generally considered slow and may be faster than emptying an existing array. You need to benchmark this before you decide.

Note that you haven't touched the old array, so it's still sitting around somewhere. Emptying the existing array vs creating a new one will have very different memory behavior, which is more likely to cause problems than the CPU cost of creating a new array object.

ssube
  • 47,010
  • 7
  • 103
  • 140