SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict jasongr's Avatar
    Join Date
    Jul 2004
    Location
    usa
    Posts
    371
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    the most efficient (size+speed) way to create an array

    Hello people

    I need a JavaScript code which defines an array of length 1000, where each entry should be initialized to 0

    My question is:
    What is the most efficient way (in JavaScript) to create such array:

    one solution would be:
    var test = [0, 0, 0, 0, ..... , 0, 0];
    repeat the zeros 1000 times

    another solution would be:
    var test = new Array(1000);
    for (var i=0; i<1000; i++) {
    test[i] = 0;
    }

    I don't want to assume that if I create the array using line
    var test = new Array(1000);
    then automaticaly every one of its cells is initialized to 0
    I am afraid that the logic might be different across browsers.
    Assumption is the root of all evil

    maybe there are some more optional ways to initialize such array
    The code
    var test = [0, 0, 0, 0, ..... , 0, 0];
    might be fast, but it is not efficient in terms of the amount of html it generates (assuming the code is embedded inside the html apge and not in a .js file)

    I am looking for a solution that is both fast, and also doesn't cause the html content to be large (increasing download time)

    regards

  2. #2
    SitePoint Addict dek's Avatar
    Join Date
    Oct 2004
    Location
    UK
    Posts
    352
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well - why not combine the approaches?

    Code:
    var test = [ ];
    while (test.length < 1000)
       test.push(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
    Only dead fish go with the flow

  3. #3
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    dek's code is good, actually only assignment to multiple elements in for loop can beat it.
    However, in javascript it's rarely needed to allocate and pre-initialize arrays.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •