最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Is JavaScript switch statement linear or constant time? - Stack Overflow

programmeradmin1浏览0评论

I have the following JavaScript on my site so that when certain specific searches are performed, the answer is hardcoded to a specific page:

function redirect() {
    var input = document.getElementById('searchBox').value.toLowerCase();

    switch (input) {
      case 'rectangular':
        window.location.replace('/');
        break;
      case 'elephant':
        window.location.replace('/');
        break;
      case 'coils':
        window.location.replace('/');
        break;
      default: // No keyword detected: submit the normal search form.
        return true;
        break;
    }
    return false; // Don't let the form submit
}

I'm wondering whether the search statement in JavaScript is linear on the number of case statements or constant time? If linear, is there a better way to write this code so it is constant time regardless of the number of special cases I code?

I have the following JavaScript on my site so that when certain specific searches are performed, the answer is hardcoded to a specific page:

function redirect() {
    var input = document.getElementById('searchBox').value.toLowerCase();

    switch (input) {
      case 'rectangular':
        window.location.replace('http://www.Example./Rectangular/');
        break;
      case 'elephant':
        window.location.replace('http://www.Example./Elephants/');
        break;
      case 'coils':
        window.location.replace('http://www.Example./Parts/');
        break;
      default: // No keyword detected: submit the normal search form.
        return true;
        break;
    }
    return false; // Don't let the form submit
}

I'm wondering whether the search statement in JavaScript is linear on the number of case statements or constant time? If linear, is there a better way to write this code so it is constant time regardless of the number of special cases I code?

Share Improve this question asked Dec 12, 2016 at 20:42 WilliamKFWilliamKF 43.2k70 gold badges203 silver badges306 bronze badges 1
  • This related question may be useful, but doesn't specifically say whether JS is optimized with jump table lookups or not. That said, your code would be much cleaner and probably faster using a simple name:value pair mapping of input and url. – Matt Johnson-Pint Commented Dec 12, 2016 at 20:58
Add a ment  | 

2 Answers 2

Reset to default 4

The spec does not make any time plexity guarantees for the switch statement. It's semantics to do require a sequential evaluation of the case expressions however, so in the general case it behaves linearly.

Engines are free to optimise the evaluation if all of the cases are constant strings or numbers (and it's fairly simple), so you can expect constant time plexity.

If you want to enforce a better-than-linear behaviour, you need to use a Map as a lookup table:

var redirects = new Map([
    ['rectangular', 'http://www.Example./Rectangular/'],
    ['elephant', 'http://www.Example./Elephants/'],
    ['coils', 'http://www.Example./Parts/']
]);
function redirect() {
    var input = document.getElementById('searchBox').value.toLowerCase();
    if (redirects.has(input)) {
        window.location.replace(redirects.get(input));
        return false; // Don't let the form submit
    } else {
        return true;
    }
}

In a pre-ES6 environment, you can also use an object for the same purpose. All engines have implemented O(1) property lookup although they're not formally required to.

Here's the equivalent of Bergi's answer in ES5. It'll be fast and also a lot easier to modify pared to what you're using now.

var _redirectlist = {
  'rectangular': 'http://www.Example./Rectangular/',
  'elephant': 'http://www.Example./Elephants/',
  'coils': 'http://www.Example./Parts/'
};

function redirect() {
  var input = document.getElementById('searchBox').value.toLowerCase();

  // Redirect if we have the input in our list
  if (_redirectlist.hasOwnProperty(input)) {
    window.location.replace(_redirectlist[input]);
    return false;
  }

  return true;
}
发布评论

评论列表(0)

  1. 暂无评论