Saturday, 15 June 2013

What is the difference between string literals and String objects in JavaScript? -


derived from

string literals (marked with double or single quotas) and strings Returned string calls (i.e., without the use of new keywords) are a primitive string in a non-constructor context returned. Javascript automatically converts primitives to string objects, so it is possible to use string object methods for primitive strings. In those instances where any method is applied to a primitive string or property lookup, JavaScript automatically wraps string primitive and calls the method or performs a property lookup.

Therefore, the string literal operation (method call) should be slow in comparison to the operation on string elements (logically) because any string on the string literally method String is converted to object (additional work) before it is applied. / P>

But in this, the result is opposite, the code runs faster than Code Block-1 Code Block-2 , both code blocks are given below: (Var i = 0; i & lt; s.length; i ++) {s.charAt (i); }

Code Block-2:

  var s = New string ('0123456789'); (Var i = 0; i & lt; s.length; i ++) {s.charAt (i); }   

The results are different in the browser but Code Block-1 is always fast Code Block-2 < / P> post-text "itemprop =" text ">

There are two main types of JavaScript, preinvites and objects. > new ss = new string ('test');

Single quote / double quote patterns are the same in terms of functionality. Apart from that, you behave Trying to do that is called auto-boxing. So what really happens is that a method of art type is applied when a primitive is converted to your cover type. Keep it simple: < There is no way of pre- var s = 'test';

What is a primitive data type, it is nothing more than an indicator for a raw data memory reference , Which tells the speed of fastest random access.

When you s.charAt (i) for example?

Since there is no example of s string , javascript Automatic s , for type , typeof object or more accurate s.valueOf (s) String is . .toString.call = [Object String] .

In the practice of automatic boxing, the s goes back and forth to the cover type according to your requirement, but the standard work is incredibly fast because you have a simple data type Are working. Although auto-boxing and Object.prototype.valueOf have different effects.

If you want to force boxing or automatically enter a primitive for your cover type, then you can use Object.prototype.valueOf , but behave Is different. Auto-boxing applies only to 'necessary' methods depending on the different types of test conditions, by changing the primitive nature of the variable. That's why you get better speed.

No comments:

Post a Comment