Because storing floating-point values uses twice as much memory as storing integer values,ECMAScript always looks for ways to convert values into integers.
我预计每个数字占用相同的内存量:64位.而MDN的文章说:“没有特定的整数类型”.任何人都知道这本书作者的意思?当整数存储为64位浮点数时(如果我有这样的权限),整数会占用更少的内存?您将在上面的链接中找到整个部分(免费样本).
解决方法
JavaScript是现在编译的,这意味着它可以在许多方面进行优化,这在语言中是不明显的.
如果一个函数中的局部变量只占用一个整数值,并且不会以任何方式暴露在函数之外,那么在编译代码时,实际上可以使用整数类型来实现.
不同浏览器的实现方式有所不同.目前看来,MS Edge在Firefox方面有很大的不同,在Firefox方面有很大的不同,而且在Chrome:http://jsperf.com/int-vs-double-implementation(没有任何区别)中,jsperf认为MS Edge是Chrome 42.)
进一步的研究:
JS引擎Spidermonkey(Firefox),V8(Chrome,Opera),JavaScriptCore(Safari),Chakra(IE)和Rhino(可能还有其他,但是更难找到实现细节)使用不同的方式使用整数类型或存储数字可能为整数.一些报价:
“To have an efficient representation of numbers and JavaScript
objects,V8 represents both of us with a 32 bits value. It uses a bit
to know if it is an object (flag = 1) or an integer (flag = 0) called
here SMall Integer or SMI because of its 31 bits.”
http://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/
“JavaScript does not have a built-in notion of an integer value,but
for efficiency JavaScriptCore will represent most integers as int32
rather than as double.”
http://trac.webkit.org/wiki/JavaScriptCore
“[…] non-double values are a 32-bit type tag and a 32-bit payload,
which is normally either a pointer or a signed 32-bit integer.”
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals
“In Windows 10 and Microsoft Edge,we’ve started optimizing Chakra’s
parser and the JIT compiler to identify non const variable
declarations of integers that are defined globally and are never
changed during the course of the execution time of the program.”