Hacker News new | ask | show | jobs
by ootachi 5260 days ago
Of course you can promise types to the JS engine. Ints in particular are easy. With modern type-inferring JITs like SpiderMonkey, an expression like "var x = 3;" will infer x to int, and there will be no type checks or unboxing. In more complex cases, you can add "|0". For example:

  function f(x) {
    x = x|0;
    ...
  }
This has the effect of forcing an int interpretation for the argument, and there will be no type checks or unboxing performed thereafter.
3 comments

Interesting. I didn't know this.

I understand that actually getting speed out of JS for binary data is still quite 'hacky' though, for instance Fabrice Bellard used Typed Arrays extensively implementing his Linux-on-Javascript project: http://bellard.org/jslinux/tech.html

but you have to admit this isn't very obvious or well documented
> Of course you can promise types to the JS engine.

Because a variable can always change types, it's actually trivially proven that in a dynamically-typed language, there will always be programs in which the type cannot be inferred.

Well, statically-typed languages have a "dynamic" type too. Consider void * in C and C++ and Object in Java and C#. You have to downcast to do anything with them. That's the equivalent of what JS is doing with its dynamic typing. The basic difference is that the "dynamic" type is the default in JS, and the static type is the default in statically-typed languages.
The premise of this article is that Javascript's pure dynamic variables lead to slowness.

I'm not sure what your point with this post was because if you litter your C/C++ code with non-static casts, it is also going to be much slower than code without casts.

The parent comment was pointing out that there exist programs in JavaScript in which the types cannot be inferred. All I was saying was that this is not unique to JavaScript, or to dynamically typed languages generally.
Statically.