What is the overhead of wrapping primitives as objects in javascript?

What if there is overhead due to the transfer of primitive JavaScript values ​​to become objects?

For instance:

> var x = Object(12); undefined > typeof x "object" > ({}).toString.call(x); "[object Number]" 

vs

 > var y = 12; undefined > typeof y "number" > ({}).toString.call(y); "[object Number]" 

My reason for asking: I am working with GWT code that converts values ​​between JavaScript and Java code (which is later compiled into Javascript code). Since Java cares a lot about types, and the GWT JSNI (interop method) supports primitives and objects, I was wondering why not just returning boxed primitives (for example, Object (12) is a boxed version of 12).

The answer is that I expected a clear speed. I didn’t understand that it would be so hard, but I explicitly avoid using Javascript primitives if you can or pay a serious price for performance. (with the caveat that the overhead from calling the method is flipped around, as Yang says)

+4
source share
2 answers

var x = Object(12); It turns out to be approximately 97% slower than var x = 12;

http://jsperf.com/object-wrap-number-overhead

However, if you intend to call a method on a number, the difference is much smaller, although it’s even faster not to call Object() on the number.


But the real question is why are you doing this? You can call methods on numbers without this explicit conversion.

 var x = 12.1234; x.toFixed(2); // "12.12" 
+3
source

Primitives are not objects, so they are less expensive (see Alex Wayne's answer). On the other hand,

You can call any of the methods of the String object in a string literal value - JavaScript automatically converts the string literal to a temporary String object, calls the method, and then deletes the temporary String object. You can also use the String.length property with a string literal.

see MDN manual

So use primitives, but if you want to call methods on them, you should create an object instead.

+3
source

Source: https://habr.com/ru/post/1482251/


All Articles