【问题标题】:Complexity between if-else, switch and regexif-else、switch 和 regex 之间的复杂性
【发布时间】:2022-01-19 15:22:49
【问题描述】:

我将优化 javascript 代码,我看到旧代码如下所示,

var emcont = $('#emcont').val();
numericMatch = emcont.match(/\d/g);
if (numericMatch == null) {
    isValid = false;
    $('#msg_emcont').html(getMessage('msg_emcont')).show();
} else if (emcont.length != 14) {
    isValid = false;
    $('#msg_emcont').html(getMessage('msg_emcont')).show();
} else if (numericMatch.length && numericMatch.length != 10) {
    isValid = false;
    $('#msg_emcont').html(getMessage('msg_emcont')).show();
} else {
    $('#msg_emcont').html('').hide();
}

我打算将 if-else 条件转换为 switch 条件,但上面代码中的问题是第二个条件验证使用了emcont 变量,所以我不能在switch 语句中直接使用numericMatch。所以我决定直接在switch 语句中使用emcont 变量,如下面的代码,

switch(emcont)
    {
        case emcont.match(/\d/g) == null:
            isValid = false;
            $('#msg_emcont').html(getMessage('msg_emcont')).show();
            break;
        case emcont.length != 14:
            isValid = false;
            $('#msg_emcont').html(getMessage('msg_emcont')).show();
            break;
         case emcont.match(/\d/g).length && emcont.match(/\d/g).length != 10:
            isValid = false;
            $('#msg_emcont').html(getMessage('msg_emcont')).show();
            break;
        default:
            $('#msg_emcont').html('').hide();
            break;
    }

在 switch case 验证中使用的正则表达式,所以我需要知道哪个代码在性能方面更好。

【问题讨论】:

  • 你不能这样使用 switch 语句。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 为什么人们认为代码迁移到交换机会更好?想让你的代码更好吗?停止一遍又一遍地在 DOM 中查找元素。
  • 你的开关应该是switch(true),但这样使用它只是不好的做法。
  • 你可以只用一个正则表达式来测试它。真的不需要3次检查。你期望的模式是什么?像 XXX-1234567890 之类的东西???

标签: javascript performance optimization complexity-theory


【解决方案1】:

请不要滥用 switch(true) 的副作用,这就是您的意思

这是干的,更容易阅读

var emcont = $('#emcont').val();
const numericMatch = emcont.match(/\d/g);
$('#msg_emcont')
  .html(getMessage('msg_emcont'))
  .toggle(
    numericMatch == null || 
    emcont.length != 14  || 
    (numericMatch.length && numericMatch.length != 10)
  )

你甚至可以考虑搬家

$('#msg_emcont').html(getMessage('msg_emcont'))

到页面加载,所以它只完成一次

【讨论】:

  • @ShriSamarth 不要亲自投票。使用 switch 来测试布尔语句是一个巨大的反模式,这是被否决的,而不是你
  • 实际上,我优化了包含很多 if-else 条件的 jquery 代码,正如我在问题中提到的那样。该代码用于平板电脑 webview。该过程是用户状态包含5大复杂的表格。我可以优化该代码的方式是什么?我的客户告诉我代码需要很长时间才能执行。
  • 确保 a) 委托接近相同的元素(如容器上的事件侦听器) b) 如果需要重用,缓存元素。我将不得不查看有问题的代码
  • 而html5表单验证大概可以摆脱必须的javascript代码。正如我在评论中所说,如果存在已知模式,所有这些长度检查都可以在一个 reg exp 检查中完成。所以代码可以更小。
猜你喜欢
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多