0

I am looking to optimize this function. It is part of a large recursive knapsack solving script and gets called several hundred times. cap and item are passed in as an int, pLimit and tLimit are arrays.

The string concatenation is causing the function to bog down.
Any ways to optimize this?

// Converts subproblem data to string for hashing
function encode(cap, item, pLimit, tLimit) {
    data = cap+","+item+","+pLimit+","+tLimit;

    return data;
}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
  • 2
    Maybe try adding all strings to an array, and at the end call `.join(",")` on the array – Ian Mar 06 '14 at 18:49
  • possible duplicate of [Fast way to concatenate strings in nodeJS/JavaScript](http://stackoverflow.com/questions/13859543/fast-way-to-concatenate-strings-in-nodejs-javascript) – Rahil Wazir Mar 06 '14 at 18:53

2 Answers2

0

The best way to optimize string concats is to use array based joining. Hold all the strings as part of array and then join these.

var parts = [ "a" , "b", "c" ];

console.log(parts.join(""));
Risto Novik
  • 8,199
  • 9
  • 50
  • 66
0

In ECMAScript6 you can use Template literals:

function encode(cap, item, pLimit, tLimit) {
    return `${cap},${item},${pLimit},${tLimit}`;
}
Alexander
  • 7,484
  • 4
  • 51
  • 65