code example: Some simple tips for optimizing the JavaScript compiler's work to get you to write faster JavaScript code for high performance running

Source: Internet
Author: User

Tells you some simple tricks to optimize the javascript compiler to work, so your JavaScript code runs faster. Especially when you find that the frame rate drops in your game or when the garbage collector has a lot of work to do.

Single State:

When you define a function with two parameters, the compiler will accept your definition, and it will be difficult to change the compiler 's work if the type, number, or type of return value of the function parameter changes. Normally, a single homomorphic data structure and the same number of parameters will make your program work better.

function example(a, b) {  // 期望a,b都为数值类型  console.log(++a * ++b);};example(); // 不佳example(1); // 仍然不佳example("1", 2); // 尤其不佳example(1, 2); // 很好

Expand

The compiler will calculate the value of the variable at compile time and expand it ( best Practice ), so you can express as much information as possible before the program executes. Constants and variables can be expanded as long as they do not use any operations related to the run time.

const a = 42; // 很容易展开const b = 1337 * 2; // 可以求值const c = a + b; // 也可以求值const d = Math.random() * c; // 只能展开‘c‘const e = "Hello " + "Medium"; // 其他类型的值也可以// 展开前a;b;c;d;e;// 展开后// 会在编译的时候做好这些!4226742716Math.random() * 2716"Hello Medium"

function Inline:

The JIT compiler will find out which parts of your code are frequently executed. The code executes faster at compile time by dividing the function into small chunks to inline the code block and the hot-traced function.

// 以下这些会内联// [?] 单一的返回语句// [?] 返回总是一样的// [?] 返回时单一同态的// [?] 参数是单一同态的// [?] 函数体是一个单一的语句// [?] 不是包裹在另一个函数体内// ...function isNumeric(n) {  return (    n >= 48 && n <= 57  );};let cc = "8".charCodeAt(0);// 内联前if (isNumeric(cc)) {}// 内联之后if (cc >= 48 && cc <= 57) {}

Declarations:

Avoid declaring functions/closures or objects in frequently called functions. Objects (including functions, objects) are pressed into the heap, and the garbage collector affects the heap, where many wat and wut need to determine the next step (like release or not)

Instead, declaring a variable will be quick, as they are pressed into the stack. For example, a function will have its own stack, the variables associated with the function will be pressed into the stack, whenever the function exits, the stack is released as well.

// 欠佳function a() {  // 决不再函数里面申明函数  // 会在每次调用函数分配资源  let doSomething = function() {    return (1);  };  return (doSomething());};let doSomething = function() {  return (1);};// 很好// 在函数外申明 ‘doSomething‘// 因此可以只调用它,而不是// 在每次调用‘b‘去申明和调用function b() {  return (doSomething());};

Parameters:

The cost of function calls is expensive (if the compiler cannot inline them). Try to use as few parameters as possible and not modify the parameters in the function body.

function mul(a, b) {  return (arguments[0]*arguments[1]); // 欠佳, 很慢  return (a*b); // 很好};function test(a, b) {  a = 5; // 欠佳, 不修改参数标识  let tmp = a; // 很好  tmp *= 2; // 可以修改伪造的 ‘a‘};

Data type:

Try to take as many numeric and Boolean types as possible, and they are much faster than other basic types in the comparison operation. For example, declaring a string type secretly causes a lot of junk data, because the string is a complex object with many preset properties.

Also, avoid double-precision floating-point numbers that operate on negative and multi-decimal numbers.

const ROBOT = 0;const HUMAN = 1;const SPIDER = 2;let E_TYPE = {  Robot: ROBOT,  Human: HUMAN,  Spider: SPIDER};// 欠佳// 避免在大任务中缓存字符串(最好在一般中场景也不)if (entity.type === "Robot") {}// 很好// 编译器会算出数值表达式// 没有深度计算会更快if (entity.type === E_TYPE.Robot) {}// 完美// 右侧的二元表达式也是可以被展开的if (entity.type === ROBOT) {}

Strict and abstract operators:

Try using the three equals sign operation such as "= = =" (strict) instead of "= =" (loose, abstract). Executing strict operators guarantees that the compiler will preset a definite value without having to compare statements in multiple cases. (such as N>0=^true), which can lead to better performance scenarios.

Strict conditions:

JavaScript provides a great syntactic sugar to allow you, for example, "if (a) then bla" code. In this case, the compiler must go to compare "a" with multiple types to determine if it is true, because it does not know the result of that type. Of course, you should use these great syntactic sugars, but in fast-executing complex functions with multiple return statements (such as null or object), you should consider the following recommendations.

Toxic:

The following list of language features will be less or block the code optimization process.

    • Eval

    • With

    • Try/catch

Object:

Object instances typically try to share a hidden class, cautiously adding a member variable to an instantiated object, because it creates a new hidden class and is a lot more complicated for the compiler (same for you)

// 隐藏类‘hc_0‘class Vector {  constructor(x, y) {    // 编译器找到并且期望的成员声明在这    this.x = x;    this.y = y;  }};// 两个vector对象共享隐藏类‘hc_0‘let vec1 = new Vector(0, 0);let vec2 = new Vector(2, 2);// 欠佳,vec2这样会创建新的隐藏类‘hc_1‘vec2.z = 0;// 很好,编译器知道这个成员vec2.x = 1;

Cycle:

Cache your array length properties, and use the array as a single homomorphism type. Usually avoid using "for." In "or loop over the array because it will be slow.

The Continue and break statements in a looping statement are faster than the IF statement body. Keep your loop clean and pack everything into a sub-function so the editor feels more comfortable. Also, using the pre-increment operator (_++ i instead of I ++_) will have a little bit of performance gain.

let badarray = [1, true, 0]; // 欠佳, 不要混合类型let array = [1, 0, 1]; // 好的用法// 不好的选择for (let key in array) {};// 更好的// 但是总是缓存数组大小let i = 0;for (; i < array.length; ++i) {  key = array[i];};// 很好let i = 0;let key = null;let length = array.length;for (; i < length; ++i) {  key = array[i];};

written at the end :forFreedom | Knowledge should be open to access, look at the outside world, and it this line, not to go to Google data, finally, Amway a V--PN agent. a red apricot VPN, to Google to check the information is the absolute first choice, the connection speed, the use is also convenient. I bought is 99¥ a year, through this link (http://my.yizhihongxing.com/aff.php?aff=2509) registered after the Member center to lose the coupon code, split down, only 7 yuan per month, special benefits.

This document tags : javascript compiler JavaScript optimized javascript tips The JavaScript compiler principle

Turn from SUN's BLOG-focus on Internet knowledge, share the spirit of the Internet!

Original Address: code example: some simple tips to optimize your JavaScript compiler's work to get you to write high-performance JavaScript code that runs faster

related reading: How to select the right JavaScript framework in a program development project, save time and Cost 9 excellent JavaScript framework introduction
Related reading: " site environment Apache + PHP + mysql xampp, how to implement a server on the configuration of multiple sites?" "

Related reading: What is the engineer culture? Why are the engineers alive? Why do I need an engineer culture as an IT or internet company? "

Related reading: useful for programmers: 2017 latest in Google's Hosts file download and summary of the various hosts encountered the problem of the solution and configuration of the detailed

related reading: the increasingly popular Gaussian blur (Gaussian Blur) and frosted glass effect (matte effect) of mobile UI design, how to use Android Renderscript simple implementation? 》

Related blog:SUN ' S blog -Focus on Internet knowledge and share the spirit of Internet! Go and see:www.whosmall.com

code example: Some simple tips for optimizing the JavaScript compiler's work to get you to write faster JavaScript code for high performance running

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.