Skip to content

Instantly share code, notes, and snippets.

@danveloper
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danveloper/cdb32b288ecf6e876a26 to your computer and use it in GitHub Desktop.
Save danveloper/cdb32b288ecf6e876a26 to your computer and use it in GitHub Desktop.
optimization question

Optimization Question

Does JavaScript optimize for a function that is defined within the context of another function?

For example, are the following examples canonically represented (in performance terms) after compilation, or is one approach favored optimally over the other?

Inner-function

function sortMyThings() {
  var a = ["b", "e", "a", "c", "d"];
  a.sort(function(a, b) {
    if (a < b) return -1;
    if (a == b) return 0;
    if (a > b) return 1;
  });
}

External Function

function sortFunc(a, b) {
  if (a < b) return -1;
  if (a == b) return 0;
  if (a > b) return 1;
}

function sortMyThings() {
  var a = ["b", "e", "a", "c", "d"];
  a.sort(sortFunc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment