对所有永远不会更改的变量使用const是有意义的吗? [英] Does it make sense to use const for all variables that will never be changed?

查看:192
本文介绍了对所有永远不会更改的变量使用const是有意义的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下所示:

const audio = React.findDOMNode(this.refs.audio);
const seeker = React.findDOMNode(this.refs.seeker);
const {left, right} = seeker.getBoundingClientRect();
const seekToPerc = (event.clientX - left) / (right - left);

audio.currentTime = this.props.totalRunTime * seekToPerc;

这是否过度使用 const ?我应该在这里使用 let

Is this overusing const? Should I be using let here?

推荐答案

使用const是直到个人。如果您假装javascript是强类型的,大多数JavaScript引擎的优化工作最好。 const 似乎是一个好主意。

The use of const is up to the individual. Optimization of most javascript engines work best if you pretend that javascript is strongly typed. const would thus seem like a good idea.

一些事实。


  • MDN表示const是块作用域,如code>让。在严格模式下,这只是真正的

  • 必须在声明中为Consts赋值。只有在严格的
    模式下才是真实的。

  • 不能重新分配Const。这在严格和正常的
    中都是如此,但是在正常的JavaScript分配到常量的时候,这个
    代表了很难找到错误的根源。 (注意没有好的
    参数不使用严格模式)

  • MDN states that consts are block scoped like let. This is only true in strict mode.
  • Consts must be assigned a value on declaration. Only true in strict mode.
  • Consts can not be reassigned. This is true in both strict and normal but in normal javascript assigning to a constant fails silently which represents a source of hard to find bugs. (NOTE there is no good argument for not using strict mode)

差异作为示例

function log(d){console.log(d);}
(function (){
    if(true){
        const a = 10;  // correctly formed use of constant
        const b;       // does not fail
        log(a);        // 10;
        log(b);        // undefined
        b = 10;        // nothing happens. If you have forgoten this is a constant
                       // you will have a hard time knowing this assignment is failing
        log(b);        // undefined
    }
    // scope not respected
    log(a); // 10 const should have block scope. This does not seem to be true
            // in normal javascript
})();

// function in strict mode
// not this is an example only and can not run. It is a compilation of several functions
(function (){
    "use strict";
    if(true){
        const a = 10;    
        const b;     // SyntaxError: Unexpected token. Javascript parsing 
                     // stops here and the function will never be called
        a = 20;      // TypeError: Assignment to constant variable
    }
    // scope is respected
    log(a); // ReferenceError: a is not defined
})();

正如你所看到的,在严格模式下使用const并没有很大的区别。除了严格的模式,使用常量是很愚蠢的。

As you can see there is a big difference between using const in strict mode and not. It would be foolhardy to use constants in anything but strict mode.

性能。
Chrome早期采用了 const ,我有使用 const 至少3年的记忆前。当我专注于图形,性能至关重要。我推断,一个 const 将提供一个非常需要的性能优势,与#define在C / C ++中通过常量值的简单代码插入一样。在那天结束的时候,我完全反对使用const,因为它的表现非常糟糕。

Performance. Chrome was very early in its adoption of const, I have memory of using const at least 3 years ago. As I specialize in graphics, performance is critical. I reasoned that a const would provide a much needed performance advantage, much the same way #define does in C/C++ by simple code insertion of the constant value. Saddly by the end of that day I was completely turned against the use of const because of it terrible performance.

从那以后,它有所改善。

Since then it has improved.

jsperfConsts V Vars

使用 const 在所有测试中始终都较慢,但它是边缘的,太接近调用。唯一的例外是阻止范围声明,其大约是 var let 的速度的1/3。一个令人惊讶的发现是, let 现在在Chrome Beta上非常快,一个月前,我不会靠近它,这个事实是我回答的原因。

Using const is consistently slower in all tests but it is marginal and too close to call. The only exception being block scope declaration where it was about 1/3rd the speed of var and let. One surprising finding is that let is now very fast on Chrome Beta, a month ago I would not go near it, this fact is the reason for my answer.

OP问...
对于永远不会更改的所有变量使用const是有意义的吗?

一年前,我会说永远不要使用它。几个月前,我会说:有一个很好的理由,但是var更好。

A year ago I would have said "NEVER USE IT". A few months ago I would have said, "Have a good reason but var is better".

现在我的答案绝对是使用常量,只要你打算一个变量永远不会更改。常数表示文字,与var一样好。

Now my answer is most definitely use constants whenever you intend a variable to never change. Constants out performs literals and are as good as var.

const c = 10;
var v = 10;
var a = 10; // this is slower 
var a = c; // this is 20% faster
var a = v; // this is about < 1% faster than const.

根据浏览器的变化率,从过去几个月的表现变化,在chrome上code> let 和 const 我会怀疑这个常数会在今年年底之前执行变量。 (请注意,我使用的是Chrome Beta 47)

At the rate of change browsers undergo, and from the performance changes in the last few months of both let and conston chrome. I would suspect that constants will out perform vars by the end of the year. (please note I am using Chrome Beta 47)

我执行的测试没有为代码优化提供太多空间,所以我猜想使用 const 这在测试中不明显。

The tests I have performed do not provide much room for code optimisation, so I would guess there is additional performance in using const that is not evident in the tests.

一个常量是其强大的类型,这给了javascript优化算法可用于提供额外的性能。

A constant by its very nature is strongly typed, this gives the javascript optimisation algorithms something to use to provide additional performance.

使用常量可以提供更好的代码质量。 Javascript(甚至严格的模式)可以长时间隐藏错误,使用常量可以减少分配不当,意外类型转换等风险。

Using constants makes for better code quality. Javascript (even strict mode) can hide a bug for a long time, using constants reduces the risk of bad assignments, accidental type conversion, and more.

但是
我对const的使用给了一个很大的警告。 仅在严格模式下使用const ,其在正常JavaScript中的行为是危险的,只会导致您出现问题。

BUT I place a big warning on the use of const. ONLY USE const in strict mode, its behaviour in normal javascript is dangerous and will only cause you problems.

这篇关于对所有永远不会更改的变量使用const是有意义的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆