Can I define my string literal to autobox to another constructor? not String()

Viewed 66

I am comparing the performance between these 2 blocks of code:

Block 1

for(var i = 0; i < 20000; i++) {
  let a = "a random string";
  a.split("");
}

and Block 2

for(var i = 0; i < 20000; i++) {
  let a = new nativeWindow.String("a random string");
  a.split("");
}

According to this page test https://jsben.ch/Nzfb1 the first block is 50 percent faster.

But I still need to use block2 because I don't want the literal string to autobox to the window.String constructor, I'd like it to autobox to the constructor I define.

Is it possible to achieve this ?

1 Answers

Caling new String(val) returns an instance object of String. It is not a primitive value, that's why it can be noticeably slower.

typeof new String('a random string') // object

In real life it is very rare case when you need to do such things. Usually String is called without new in order to simply convert value to string. In that case String('random string') will just return the same primitive value you passed in.

typeof String('a random string') // string

Try to add the third block to your tests:

for(var i = 0; i < 20000; i++) {
  let a = String("a random string"); // no 'new'
  a.split("");
}

And you will see that its performance is almost the same as for the simple initialisation like in your first block.

UPD: According to tests, in some browsers the first block from the question still executes few times faster than one above. It probably happens because String(val) is a function call, what makes browser to do more actions than during simple initialisation. Anyway, the main point of this answer is that creating object is slower than simple initialisation and it is quite unusual for String to be used like a constructor.

Related