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

List.sortBy has serious performance issue #485

Closed
jvoigtlaender opened this Issue Jan 17, 2016 · 2 comments

Comments

Projects
None yet
1 participant
@jvoigtlaender
Contributor

jvoigtlaender commented Jan 17, 2016

Let's say I call List.sortBy f on a list of length 3, where the following is true:

  • Computing f for any input is extremely expensive.

That List.sortBy is reduced to a call of JavaScript's sort function on arrays. I don't know what sorting algorithm JavaScript implementations use, but it doesn't really matter. What matters is that due to the way List.sortBy is currently reduced to JavaScript's sort, the following is true:

  • Function f is called at least four times. (It might even be six times.)

Very bad! At least one time too many.

A better strategy would be (essentially, though in details this can be even further improved):

List.newSortBy f = List.map snd << List.oldSortBy fst << List.map (\a -> (f a,a))

This new code is guaranteed to induce only three calls of f for an input list of length 3.

Since I can make f arbitrarily expensive to compute on certain arguments, I can give calls of the current implementation of List.sortBy that are arbitrarily (even asymptotically) more expensive than the proposed alternative. (The converse is not true. The new implementation is guaranteed to not be asymptotically worse than the current implementation.)

@jvoigtlaender

This comment has been minimized.

Show comment
Hide comment
@jvoigtlaender

jvoigtlaender Jan 17, 2016

Contributor

For comparison, see the Haskell standard library version of this function: https://hackage.haskell.org/package/base-4.8.1.0/docs/Data-List.html#v:sortOn

Contributor

jvoigtlaender commented Jan 17, 2016

For comparison, see the Haskell standard library version of this function: https://hackage.haskell.org/package/base-4.8.1.0/docs/Data-List.html#v:sortOn

@jvoigtlaender

This comment has been minimized.

Show comment
Hide comment
@jvoigtlaender
Contributor

jvoigtlaender commented May 29, 2016

Replaced by pull request: https://github.com/elm-lang/core/pull/631.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment