GUIDES Optimizing Embedded JavaScript Building a String
About
Binary Data
Index
Convert String to ArrayBuffer
Convert ArrayBuffer to String
Convert ArrayBuffers to String
Handle Errors Converting ArrayBuffer to String
Immutable ArrayBuffers
Resize an ArrayBuffer
Combine ArrayBuffers
Convert Base64 to Binary Data
Convert Binary Data to Base64
Convert Binary Data to Hex
Convert Hex to Binary Data
Calculate CRC for Binary Data
Compress Binary Data – One Buffer
Compress Binary Data – Streaming
Decompress Binary Data – One Buffer
Decompress Binary Data – Streaming
Callbacks
Index
One-Time Callback
Repeating Callback
Repeating Callback with Initial Delay
Immediate Callback
Reschedule Callback
Cancel Callback
Suspend Callback
What About setTimeout?
Optimizing Embedded JavaScript
Index
When to Optimize
Know Where to Optimize
Looping through an Array
Iterating Over a String
Building a String
Avoid Copying Buffers
Accessing Properties
Map versus Object
Appending to an Array
Operating on Bits
Defining Class Methods
Reducing Stack Use
Time
Index
Get Unix Time
Get Time of Day
Get Date
Get Time Since System Start
Get Microseconds
Set System Date and Time
Set Real-Time Clock Time
Get Time and Date from Network
Get Time and Date from Real-Time Clock
Sleep

Building a String

When building a string from several pieces, it is common to use the addition operator to combine the pieces. This approach is simple and, for a few small strings, it is also reasonably efficient. Even more efficient is concat(), which eliminates memory used for intermediate results.

/* BEFORE */
let s1 = "one";
let string = s1 + 2 + "three";
// => "one2three"

/* AFTER */
let s1 = "one";
let string = s1.concat(2, "three");
// => "one2three"

If you have more than a few substrings to combine, concat() may be impractical. A good alternative is creating an array of the substrings and combining them with join() .

let array = [];
array.push("one");
array.push(2, "three");
array.join("");
// => "one2three"

As an added bonus, if you need a separator between the substrings, join() makes that easy.

let array = ["one", 2, "three"];
array.join("-");
// => "one-2-three"

Note: Using + to build long, complex strings is so common among web developers that the JavaScript engines in web browsers have sophisticated optimizations that make it just as fast as the techniques described above. To keep the engine size small, those optimizations aren't available to Embedded JavaScript developers. Fortunately, Embedded JavaScript developers don't tend to work with large strings often.