【问题标题】:Javascript null check performance (compare if and try/catch)Javascript null 检查性能(比较 if 和 try/catch)
【发布时间】:2020-06-24 08:01:45
【问题描述】:

我必须得到一个内部组件的值。仅出于性能比较时,哪个更好 1 或 2,此方法被多次调用。 foo 可能为 null,具体取决于运行时,但 foo 可能有值,但 bar 可能为 null 等。这不是错误情况或者 foo、bar、innerfoo、innerbar 中的任何一个为 null 的意外情况,它们中的任何一个在运行时都可以为 null,具体取决于层次结构。但是 innerbar 不能有 if foo 为 null 的任何值,因此如果 foo 未定义,则无需检查内部组件。

//1
function getInnerValue() {
    if (foo && foo.bar && foo.bar.innerfoo && foo.bar.innerfoo && foo.bar.innerfoo.innerbar) {
        return foo.bar.innerfoo.innerbar.x;
    }
    return 0;
}

//2
function getInnerValue() {
    try {
        return foo.bar.innerfoo.innerbar.x;
    }
    catch (e) {
        return 0;
    }
}

【问题讨论】:

标签: javascript performance null try-catch undefined


【解决方案1】:

任何带有 try catch 的东西一旦被触发都会对性能造成很大的影响。

就我个人而言,我没有发现长长的真值检查链比 try catch 块更具可读性。只是更长,丑陋和冗长。但真的,有人会在阅读(或编辑)时遇到困难吗?或者更确切地说,您是否需要阅读它才能了解它在做什么?
事实上,如果有任何东西,try catch 块感觉更像是一种 hack。我仍然要考虑为什么我要尝试捕获异常,而且它仍然很丑。

无论如何,我们现在有了可选链接,所以上面的内容甚至不再重要了。我会选择return x?.y?.z?.a?.b?.c?.d||0之类的东西。

您当然可以使用保护函数,因为您可能已经注意到阅读您链接的线程。像 lodash _.get 或你自己的守卫(a,'b','c','d')。

optional chaining browser compatibility

Babel transpiled output of optional chaining

如果 x 为 null 或未定义,x?.y 将立即返回 undefined
浏览器兼容性相对较新。检查兼容性表。您应该将 Babel 转译添加到您的管道中。

没有转译的可选链接:

foo = {}
function fn() {
  if (foo?.bar?.innerfoo?.innerbar)
      return foo.bar.innerfoo.innerbar.x
  return 0
}

console.log(fn())

foo = {bar: { innerfoo: { innerbar: { x: 5 }}}}

console.log(fn())

转译代码:

foo = {}
function fn() {
  var _foo, _foo$bar, _foo$bar$innerfoo;

  if ((_foo = foo) === null || _foo === void 0 ? void 0 : (_foo$bar = _foo.bar) === null || _foo$bar === void 0 ? void 0 : (_foo$bar$innerfoo = _foo$bar.innerfoo) === null || _foo$bar$innerfoo === void 0 ? void 0 : _foo$bar$innerfoo.innerbar) return foo.bar.innerfoo.innerbar.x;
  return 0;
}

console.log(fn())

foo = {bar: { innerfoo: { innerbar: { x: 5 }}}}

console.log(fn())

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 2010-09-14
    • 2012-04-03
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多