Array.prototype.remove(item)
Bob Myers
rtm at gol.com
Fri Nov 10 12:24:09 UTC 2017
Thanks for your optimization. In one of my library routines I further
optimize this with
```js
if (elt === item) {
changed = true;
} else {
if (changed) { array[j] = elt; }
j++;
}
```
To avoid unnecessary assignments (which might be expensive--I don't know,
are they?) while you're still in the portion of the array before the first
element to be removed.
On Fri, Nov 10, 2017 at 5:39 PM, T.J. Crowder <
tj.crowder at farsightsoftware.com> wrote:
> On Fri, Nov 10, 2017 at 11:41 AM, Bob Myers <rtm at gol.com> wrote:
> >
> > What's wrong with this?
>
> I had the impression he was trying to avoid callbacks, just using `===`.
> But other than a missing `const` on the `for-of`, it looks nice and
> efficient -- except that [it doesn't seem like `for-of` on arrays with the
> default iterator is much optimized yet][1]. FWIW:
>
> ```js
> function removeFromArray(array, item) {
> let changed = false;
> let j, i, len, elt;
>
> for (j = i = 0, len = array.length; i < len; ++i) {
> elt = array[i];
> if (elt === item) {
> changed = true;
> } else {
> array[j++] = elt;
> }
> }
>
> array.length = j;
> return changed;
> }
> ```
>
> Clunkier but apparently we're optimizing for speed...
>
> -- T.J. Crowder
>
> [1]: https://jsperf.com/for-of-vs-for-with-const-binding/1
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20171110/106ce699/attachment.html>
More information about the es-discuss
mailing list