如果我是一个虚拟机,在执行 JavaScript 时我会如何处理数字?
我一直在思考如何最好地弥合 CLR 世界(.NET 运行时)和 JavaScript 之间的差距,我想到的一件事是 JavaScript 中类型的概念,它在某种程度上是从使用中推断出来的,而 ie C# 则不然。不需要这样做。
我想更多地了解 JavaScript 引擎的实现细节,特别是关于如何处理数字的细节。该标准概述了一系列在某些上下文中有效并产生某些特定结果的运算,严格来说,JavaScript 中不存在整数的概念,但存在典型的整数算术运算,例如位移位 (> >
),它始终对 32 位有符号整数进行操作,并且始终生成 32 位有符号整数。
我想最困难的部分是弄清楚数字何时是整数以及何时不是整数。但虚拟机是如何做到这一点的呢?
var x = 1; // is this an integer or a double?
var x = 1.0; // is this an integer or a double?
var x = 2147483648; // is this an integer or a double?
var x = 9007199254740993; // is this an integer, double or runtime error?
我猜这其中有很多启发式的内容。我专门寻找一些潜在的主题,可以用来更好地推理这些事情。
另外,从性能角度来看,如果您意识到某些数字被用作整数,那么您绝对可以通过坚持使用整数来优化这些情况。但是,你怎么知道什么时候应该这样做呢?
有哪位 JavaScript VM 专家愿意尝试一下吗? (此时我对虚拟机的内部结构比规范的实际细节更感兴趣)
I've been thinking about how to best bridge the gap between CLR world (.NET runtime) and JavaScript and one thing that came to mind was this notion of a type in JavaScript that it is somewhat inferred from the usage while i.e. C# doesn't need to do this.
I'd like to know a little more about the implementation specifics of JavaScript engines specifically regard how your treat a number. The standard outlines a series of operations that are valid in certain contexts and yields certain specific results, strictly speaking, the concept of an integer doesn't exist in JavaScript but there are typical integer arithmetic operations such as bit shift (>>
) which always operate on a 32-bit signed integer and always yields a 32-bit signed integer.
I guess the hard part is figuring out when a number is an integer and when a number isn't an integer. But how does VMs do this?
var x = 1; // is this an integer or a double?
var x = 1.0; // is this an integer or a double?
var x = 2147483648; // is this an integer or a double?
var x = 9007199254740993; // is this an integer, double or runtime error?
I'm guessing there's a lot of heuristics that goes into this. I'm specifically looking for some underlying theme that can be sort of used to better reason about these things.
Also from a performance perspective if you realizes that certain numbers are used as integer you can absolutely optimize those situations by sticking to integers. Though, how do you know when to do this?
Any JavaScript VM gurus out there who'd like to take a stab at this? (at this point I'm more interested in the internals of the VM than the actual specifics of the specification)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想深入了解 JavaScript 实现如何处理
Number
类型的具体细节,没有什么比查看源代码更好的了。我会查看:If you want to get into the nuts-and-bolts of how JavaScript implementations handle the
Number
type, there's nothing like going to the source. I'd look at: