IT정리노트

블로그 이미지

Edward. K

메멘토적 기억능력을 소유한 개발자 노트.

Optimizing JavaScript code

Programming/JavaScript 2009. 6. 30. 14:34
반응형
링크 : Optimizing JavaScript code
          see alse : IE+JScript Performance Recommendations Part 3: JavaScript Code inefficiencies


Optimizing JavaScript code

Authors: Gregory Baker, Software Engineer on GMail & Erik Arvidsson, Software Engineer on Google Chrome

Recommended experience: Working knowledge of JavaScript

Client-side scripting can make your application dynamic and active, but the browser's interpretation of this code can itself introduce inefficiencies, and the performance of different constructs varies from client to client. Here we discuss a few tips and best practices to optimize your JavaScript code.

Working with Strings

String concatenation causes major problems with Internet Explorer 6 and 7 garbage collection performance. Although these issues have been addressed in Internet Explorer 8 -- concatenating is actually slightly more efficient on IE8 and other non-IE browsers such as Chrome -- if a significant portion of your user population uses Internet Explorer 6 or 7, you should pay serious attention to the way you build your strings.

Consider this example:
var veryLongMessage =
'This is a long string that due to our strict line length limit of' +
maxCharsPerLine +
' characters per line must be wrapped. ' +
percentWhoDislike +
'% of engineers dislike this rule. The line length limit is for ' +
' style purposes, but we don't want it to have a performance impact.' +
' So the question is how should we do the wrapping?';

Instead of concatenation, try using a join:
var veryLongMessage =
['This is a long string that due to our strict line length limit of',
maxCharsPerLine,
' characters per line must be wrapped. ',
percentWhoDislike,
'% of engineers dislike this rule. The line length limit is for ',
' style purposes, but we don't want it to have a performance impact.',
' So the question is how should we do the wrapping?'
].join();

Similarly, building up a string across conditional statements and/or loops by using concatenation can be very inefficient.

The wrong way:
var fibonacciStr = 'First 20 Fibonacci Numbers
';
for (var i = 0; i < 20; i++) {
fibonacciStr += i + ' = ' + fibonacci(i) + '
';
}

The right way:
var strBuilder = ['First 20 fibonacci numbers:'];
for (var i = 0; i < 20; i++) {
  strBuilder.push(i, ' = ', fibonacci(i));
}
var fibonacciStr = strBuilder.join('');

Building strings with portions coming from helper functions

Build up long strings by passing string builders (either an array or a helper class) into functions, to avoid temporary result strings.

For example, assuming buildMenuItemHtml_ needs to build up a string from literals and variables and would use a string builder internally,
instead of using:
var strBuilder = [];
for (var i = 0; i < menuItems.length; i++) {
  strBuilder.push(this.buildMenuItemHtml_(menuItems[i]));
}
var menuHtml = strBuilder.join();

Use:
var strBuilder = [];
for (var i = 0; i < menuItems.length; i++) {
  this.buildMenuItem_(menuItems[i], strBuilder);
}
var menuHtml = strBuilder.join();

Defining class methods

The following is inefficient, as each time a instance of baz.Bar is constructed, a new function and closure is created for foo:

baz.Bar = function() {
  // constructor body
  this.foo = function() {
  // method body
  };
}

The preferred approach is:
baz.Bar = function() {
  // constructor body
};
baz.Bar.prototype.foo = function() {
  // method body
};

With this approach, no matter how many instances of baz.Bar are constructed, only a single function is ever created for foo, and no closures are created.

Initializing instance variables

Place instance variable declaration/initialization on the prototype for instance variables with value type (rather than reference type) initialization values (i.e. values of type number, Boolean, null, undefined, or string). This avoids unnecessarily running the initialization code each time the constructor is called. (This can't be done for instance variables whose initial value is dependent on arguments to the constructor, or some other state at time of construction.)

For example, instead of:

foo.Bar = function() {
  this.prop1_ = 4;
  this.prop2_ = true;
  this.prop3_ = [];
  this.prop4_ = 'blah';
};

Use:

foo.Bar = function() {
  this.prop3_ = [];
};

foo.Bar.prototype.prop1_ = 4;

foo.Bar.prototype.prop2_ = true;

foo.Bar.prototype.prop4_ = 'blah';

Be careful using closures

Closures are a powerful and useful feature of JavaScript; however, they have several drawbacks, including:

  • They are the most common source of memory leaks.
  • Creating a closure is significantly slower then creating an inner function without a closure, and much slower than reusing a static function. For example:

    function setupAlertTimeout() {
      var msg = 'Message to alert';
      window.setTimeout(function() { alert(msg); }, 100);
    }

    is slower than:

    function setupAlertTimeout() {
      window.setTimeout(function() {
        var msg = 'Message to alert';
        alert(msg);
      }, 100);
    }

    which is slower than:

    function alertMsg() {
      var msg = 'Message to alert';
      alert(msg);
    }

    function setupAlertTimeout() {
      window.setTimeout(alertMsg, 100);
    }
  • They add a level to the scope chain. When the browser resolves properties, each level of the scope chain must be checked. In the following example:

    var a = 'a';

    function createFunctionWithClosure() {
      var b = 'b';
      return function () {
        var c = 'c';
        a;
        b;
        c;
      };
    }

    var f = createFunctionWithClosure();
    f();

    when f is invoked, referencing a is slower than referencing b, which is slower than referencing c.

See IE+JScript Performance Recommendations Part 3: JavaScript Code inefficiencies for information on when to use closures with IE.



반응형
저작자표시 비영리 변경금지 (새창열림)
Posted by Edward. K
블로그 이미지

메멘토적 기억능력을 소유한 개발자 노트.

by Edward. K

공지사항

    최근...

  • 포스트
  • 댓글
  • 트랙백
  • 더 보기

태그

  • eclipse plugin
  • flex
  • toad
  • netbeans
  • 개한민국
  • ERwin
  • 이클립스
  • 컴퓨터 관리
  • EkNote
  • 플래시 게임
  • 캡쳐툴
  • 가상화폐무료
  • tomcat
  • sqlgate
  • egov
  • rocketdock
  • 중독성게임
  • Eclipse
  • 전자정부프레임워크
  • Flash Player
  • 미네르바
  • 사업 이야기
  • iBATIS
  • 색상코드표
  • 이미지 편집
  • Jboss
  • STS
  • EditPlus
  • Graphic
  • android

글 보관함

«   2026/01   »
일 월 화 수 목 금 토
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

링크

카테고리

분류 전체보기 (792)
행운이와함께 (1)
EkNote Project (18)
ARIS (0)
Android (2)
LINK (39)
UML (9)
Programming (154)
Cobol (0)
ASP (0)
CSS (5)
C_C++ (2)
IBatis (2)
JSP (3)
JAVA (76)
JavaScript (44)
PHP (2)
Utility (76)
Protable (3)
MobileProgram (4)
SKT (0)
KTF (0)
LGT (0)
자료들 (4)
DB (82)
mongoDB (0)
MySQL (8)
Oracle (61)
MSSQL (4)
Graphic (8)
Flash (3)
PhotoShop (3)
SourceFactory (4)
Collection (73)
작가의기막힌상상력 (14)
미소를찾아보는공간 (44)
내심장은작동중일까 (6)
멀더와스컬리의노트 (3)
이건어디에사용할까 (6)
Edward (275)
나만 알기엔 아까워 (100)
기억하기 위한 기록 (123)
시선이 머무는 공간 (50)
숨기고 싶은 이야기 (2)

카운터

Total
Today
Yesterday
방명록 : 관리자 : 글쓰기
Edward. K's Blog is powered by daumkakao
Skin info material T Mark3 by 뭐하라
favicon

IT정리노트

메멘토적 기억능력을 소유한 개발자 노트.

  • 태그
  • 링크 추가
  • 방명록

관리자 메뉴

  • 관리자 모드
  • 글쓰기
  • 분류 전체보기 (792)
    • 행운이와함께 (1)
    • EkNote Project (18)
    • ARIS (0)
    • Android (2)
    • LINK (39)
    • UML (9)
    • Programming (154)
      • Cobol (0)
      • ASP (0)
      • CSS (5)
      • C_C++ (2)
      • IBatis (2)
      • JSP (3)
      • JAVA (76)
      • JavaScript (44)
      • PHP (2)
    • Utility (76)
      • Protable (3)
    • MobileProgram (4)
      • SKT (0)
      • KTF (0)
      • LGT (0)
      • 자료들 (4)
    • DB (82)
      • mongoDB (0)
      • MySQL (8)
      • Oracle (61)
      • MSSQL (4)
    • Graphic (8)
      • Flash (3)
      • PhotoShop (3)
    • SourceFactory (4)
    • Collection (73)
      • 작가의기막힌상상력 (14)
      • 미소를찾아보는공간 (44)
      • 내심장은작동중일까 (6)
      • 멀더와스컬리의노트 (3)
      • 이건어디에사용할까 (6)
    • Edward (275)
      • 나만 알기엔 아까워 (100)
      • 기억하기 위한 기록 (123)
      • 시선이 머무는 공간 (50)
      • 숨기고 싶은 이야기 (2)

카테고리

PC화면 보기 티스토리 Daum

티스토리툴바