Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unreasonably slow alternatives to lodash functions #400

Open
valadaptive opened this issue Jun 29, 2024 · 1 comment · May be fixed by #401
Open

Remove unreasonably slow alternatives to lodash functions #400

valadaptive opened this issue Jun 29, 2024 · 1 comment · May be fixed by #401

Comments

@valadaptive
Copy link

valadaptive commented Jun 29, 2024

I haven't comprehensively looked over the list of alternatives, but just as an example, one of the listed alternatives to _.last(numbers) is:

[].concat(numbers).pop()

It is even listed twice since it "works with undefined/null":

// Native (works even with potentially undefined/null)
[].concat(undefined).pop()

While this code is certainly clever, it's also slow. It creates an entire copy of the source array in memory, and if someone uses this code in a loop, it could easily go quadratic.

I believe that code like this which "prematurely pessimizes" common operations should not be listed as an example.

@binury
Copy link

binury commented Jul 3, 2024

Hi 👋

I believe that code like this which "prematurely pessimizes" common operations should not be listed as an example.

The reason that was added (seven years ago) was to replicate the behavior of Lodash which is pessimistic about the existence of the input. Replicating Lodash should be the purpose of this repository, of course, so that flexibility is a requirement.
Now, whether that is performant is important. But, Lodash is not training-wheels for JS in the same way that jQuery was... it should be pretty obvious to most developers how to access the last element of an array. The point of its inclusion in Lodash was for brevity and convenience in a time before default arguments and optional-chaining existed as language features (and had majority browser support).

IMO, these examples could be replaced with the actual implementation which is relatively brief:
https://github.com/lodash/lodash/blob/ddfd9b11a0126db2302cb70ec9973b66baec0975/lodash.js#L7595-L7612

function last(array) {
  var length = array == null ? 0 : array.length;
  return length ? array[length - 1] : undefined;
}

@binury binury linked a pull request Jul 3, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants