简体   繁体   English

为什么 JavaScript 原语是不可变的? 这似乎效率低下

[英]Why are JavaScript primitives immutable? This seems inefficient

This is not really a question per se, but I am looking for information on why JavaScript creates a new value whenever something is reassigned.这本身并不是一个真正的问题,但我正在寻找有关为什么 JavaScript 在重新分配某些内容时会创建新值的信息。

For example, a for loop:例如,一个for循环:

for(let i = 0; i < 1000; i++)
   console.log(i);

I have researched that all primitives are immutable and reassigning them actually creates a new value in memory, why not overwrite the existing address?我研究过所有原语都是不可变的,重新分配它们实际上会在内存中创建一个新值,为什么不覆盖现有地址呢?

It seems inefficient that a for loop running will create 100 unused locations when it completes when it could have used 1. It seems strange to me, but I am sure there is a valid reason for it?一个for循环运行在完成时会创建 100 个未使用的位置,而它本来可以使用 1,这似乎效率低下。这对我来说似乎很奇怪,但我确信它有正当理由吗?

Reassigning a primitive value to a variable overwrites the value at the address that the variable points to with a copy of the primitive value.将原始值重新分配给变量会用原始值的副本覆盖变量指向的地址处的值。

This loop will overwrite the value at the address that the variable i points to 1000 times.此循环将覆盖变量i指向的地址处的值 1000 次。 It will not allocate 1000 addresses in memory.它不会在内存中分配 1000 个地址。

for(let i = 0; i < 1000; i++) {console.log(i);}

What is true is that if you assign to a variable a primitive value from another variable the value will be copied and both variables would point to different locations in memory.正确的是,如果您将另一个变量的原始值分配给一个变量,则该值将被复制,并且两个变量将指向内存中的不同位置。 You can check it:你可以检查它:

let a = 10;
let b = a; // the value 10 from a gets copied to b
a = 20; // the value 10 gets overwritten by 20 in a
console.log(b); // prints 10

Edit:编辑:

To answer the question directly: saying that js primitive values are immutable is another way of saying that they get assigned by value as opposed to arrays and objects that get assigned by reference (or are mutable).直接回答这个问题:说 js 原始值是不可变的,是另一种说法,它们是按值分配的,而不是通过引用分配(或可变)的数组和对象。

Whether a new memory allocation happens or not on each assignment of a primitive value to a variable is an implementation detail, but you can trust that it is done in the most efficient way by modern js engines.每次将原始值分配给变量时是否发生新的内存分配是一个实现细节,但您可以相信它是现代 js 引擎以最有效的方式完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM