Performance Optimization of type conversion in javascript

Source: Internet
Author: User

1. convert a number into a String and apply "" + 1. Although it looks ugly, the efficiency is actually the highest. In terms of performance: ("" +)> String ()>. toString ()> new String (): internal operations that can be used during compilation are faster than those used during running. String () is an internal function, so the speed is very fast, and. toString () is used to query functions in the prototype, so the speed is inferior. new String () is used to return an exact copy.

2. converting a floating point to an integer is more prone to errors. Many people prefer parseInt (). In fact, parseInt () is used to convert a string to a number, rather than converting between a floating point and an integer, we should use Math. floor () or Math. round (). In addition, Math is an internal object, which is different from the problem in Object Search in section 2. Therefore, Math. floor () does not actually have many query methods and call times, and the speed is the fastest.

3. for custom objects, if the toString () method is defined for type conversion, we recommend that you explicitly call toString (), because after all the possibilities of internal operations are attempted, will try to convert the toString () method of the object.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.