First function:
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.