问题
I'm reading Professional JavaScript for Web Developers 3rd ed. and in the summary of chapter 4 one can read:
Two types of values can be stored in JavaScript variables: primitive values and reference values. Primitive values have one of the five primitive data types: Undefined, Null, Boolean, Number, and String. Primitive and reference values have the following characteristics:
- Primitive values are of a fixed size and so are stored in memory on the stack.
But I can have different strings, say:
var a = "ABC";
// or
var b = "Some very irritatingly long string..."
They clearly differ in size, so how can they be allocated on the stack?
I believe the same question can be asked about numbers...
So I am for sure missing something important here.
Can someone explain why strings/numbers are of fixed size and how they can be stored on stack?
回答1:
Strings (and usually numbers) are not of fixed size, and are not stored in their entirety on the stack, but within the language they behave as if they could be stored on the stack.
It's up to the one implementing the language to decide how to store the data internally. Often the data is stored in different ways depending on the value.
Although numbers in JavaScript always behave as double precision floating point numbers, usually numbers are stored differently when they happen to be integer values. Some JavaScript engines uses unused double values as integer values, some others store integers in the value itself and double values on the heap.
For strings some of the data can be stored in an item on the stack, for example the length and a reference to the string content stored on the heap. For short strings the characters could fit in the value in the stack in place of the reference, and thus need no extra data on the heap.
回答2:
Primitive values are of a fixed size and so are stored in memory on the stack.
This seems wrong on several levels.
First, as you point out, they are not of a fixed size.
Second, even if they were, that is not necessarily a reason for storing them on the "stack".
Third, I don't even know what the "stack" is. Generally, "stack" is a term used in the context of compiled languages, most often referring to a list of invocation frames containing local variables. How JS engines store information is a matter of their internal implementation. They may use stack-like constructs, or not, or use them for some things, and not other things, or use one heap, or many heaps, or stacks containing things that point into a heap. In any case, the traditional notion of "stack" does not apply to the extent that JS supports lexical closures that require maintaining variable bindings after a function completes executing.
In any case, for the JS programmer, worrying about stacks and heaps is somewhere between meaningless and distracting. It's more important to understand the behavior of various types of values.
来源:https://stackoverflow.com/questions/33125547/javascript-string-stored-on-stack