简体   繁体   中英

Memory allocation for strings and arrays in JavaScript

First function:

  1. concatenate string and integer into one string.
  2. insert result string into an array.
  3. join all array's strings into one string.

Second function does the same, but instead of concatenation, it inserts 2 strings in the array.

Question: How do you figure out what function will allocate less memory? One more question: How many strings in memory (for each iteration) for first function we will have? For example, for 1st iteration we will have only "a0" or "a0", "a" and "0"?

function joinLetters() {
    var arr = [];

    for(var i = 0; i < 10000; i++) {
        arr.push('a' + i);
    }
    return arr.join('');
}

function joinLetters2() {
    var arr = [];

    for(var i = 0; i < 10000; i++) {
        arr.push('a');
        arr.push(i.toString());
    }
    return arr.join('');
}

joinLetters in the inner loop makes a single push, joinLetters2 does two push instead.

So you will have in the first case arr.length = 10000 , while in the second arr.length = 20000 .

Definitely you can expect the second function to be more memory expensive then the first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM