What constitutes to being mutable? If you look at the literal meaning of being mutable, it means something that can change, hence by that logic immutable would mean it cannot change. So when we say that a string is immutable we can think of the literal meaning and determine that it cannot change i.e. we cannot re-assign values to a string without re-initialising it. Makes sense doesn’t it?
let name = "Bhuman"; //first name only name += "Soni"; //append last name to it //now let's append an address to it name += "\n"; //append a new line name += "42 Wallaby way Sydney"; //add an address to it console.log(name); /*should print 'Bhuman Soni 42 Wallaby way Sydney' to console*/
The above can be explained as follows
- Initialise a variable name with value “Bhuman”
- Concatenate the last name ‘Soni’ to the variable name which now points to a newly created space in memory, while marking the old memory space for garbage collection
- Concatenate a new line character to name hence re-initialising it and pointing to a new memory space
- Lastly, concatenate the address string to the name variable, again re-initialising it and pointing to a new memory space
You can also read an article on MDN to understand this concept.
You see the problem above? Re-initialising the string every time we append a value can result in bad performance when we doing it for a several strings. Example: say we are building a large string as we read/process a large csv file, we have to re-initialise the string every time. Therefore finding a new empty memory block every time and pointing to it. Over time this would end up being a very expensive process, hence not very efficient. So how do we solve it?
Salesforce Commerce Cloud StringWriter
In Salesforce Commerce Cloud, we can solve it using the StringWriter class. You can know more about it in the official documentation
It’s a JSP so you cannot bookmark the class, you would just have to enter StringWriter in the search box. Have a look at the screenshot below to see how
Here’s the code on how to use the StringWriter
var StringWriter = require("dw/io/StringWriter"); var nameAndAdd = new StringWriter(); // create a variable nameAndAdd.write("Bhuman"); nameAndAdd.write("Soni"); // append the last name nameAndAdd.write("\n"); // append a new line nameAndAdd.write("42 Wallaby way Sydney"); // append address //now let's get the final string var finalString = nameAndAdd.toString(); /*should have 'Bhuman Soni 42 Wallaby way Sydney' to console*/
As usual, if you find any of my posts useful support me by buying or even trying one of my apps on the App Store.
Also, if you can leave a review on the App Store or Google Play Store, that would help too.