String concaternation in javascript

Viewed 88

I try to build and a JSON object which eventually will save to a file. But I found out if I use to approach one "element+= element", it will throw "Invalid string length" String. But for approach 2, I can concat a very long String and save a file. (The file is approximate 50mb). So i want to know what is wrong with my first approach?

const person = {
    id: 1,
    name: "john"
}
personJson = JSON.stringify(person);
personJson = personJson + ',';

let element = personJson;
for (let index = 0; index < 500; index++) {
     element += element; 
}
let element = personJson;
for (let index = 0; index < 100000; index++) {
     element = element + personJson; 
}
3 Answers

In both the approaches you're producing different results i.e. Suppose personJson contains string "ab"

  1. element = element + element; is producing the results

    "ab" + "ab"
    
    "abab" + "abab"
    
    "abababab" + "abababab"
    

and so on... That's why string length is increasing exponentially.

  1. element = element + personJson;

    "ab" + "ab"
    
    "abab" + "ab"
    
    "abababab" + "ab"
    

and so on... which makes your string length grow linear.

For better understanding, run below code and see the result:

const person = {
    id: 1,
    name: "john"
}
personJson = JSON.stringify(person);
personJson = personJson + ',';

let element = personJson;
for (let index = 0; index < 500; index++) {
     element += element;
     console.log(element.length); 
}

As pointed out in the comment, this is probably not the best way to encode JSON.

Regarding the reason why it happens, it is because your first loop is actually multiplying the size by 2 every iteration, so it increases exponentially. It reaches a size well above your second loop pretty quickly, and finally exceeds the maximum size allowed for a string by your javascript engine.

index = 0 ; length = 23
index = 1 ; length = 46
index = 2 ; length = 92
...
index = 24 ; length = 385875968
index = 25 ; length = 771751936

You can create an array of objects as much as you want to add to the array. Like:

const persons= [] ;
persons.push({id:1 , name: 'Shayan' });
persons.push({id:2 , name: 'john' });
...
Related