Which code is efficient?

Way 01:
I push every item in an array using a loop then make them join and send this.

app.get("/repeat/:str/:num", function(req, res){
    var num = Number(req.params.num);
    var word = [];
    for(var i = 0; i < num; i++){
        word.push(req.params.str);
    }
    var result = word.join(" ");
    res.send(result);
});

Way 02:
I just continuously add all items with an empty string using a loop and send this.

app.get("/repeat/:str/:num", function(req, res){
   var num = Number(req.params.num);
   var str = req.params.str;
   var result = "";
   for(var i = 0; i < num; i++){
       result += ' ' + str;
   }
   res.send(result);
});

Which is more efficient here?

Fewer temporary data structures and fewer passes through data is typically more efficient.

So, #2 is probably more efficient.

1 Like