How you work with Strings can have big impact on the performance of you script. This is something that is not well known or practiced. If you haven't read this before, read carefully and remember well. This is important.
+ Instead of +=With String literals, the performance gain in Mozilla is exponential. By concatenating string literals, the resulting value is interpreted and assigned to s when the script is interpreted.
An equivalent benefit can occur in Mozilla when using a local variable that does not change in value.
| Ease | Effectiveness | Overall Practicality | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 8 |
|
9 |
+ Instead of +=| Ease | Effectiveness | Overall Practicality | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 8 |
|
9 |
The example uses the following variables:
var h = "hello "; // create a string (1). var d = "drunken "; // create a string (2). var w = "world "; // create a string. (3).How many String objects are created in the example below?
var s = h; s += d; // create a new string "hello drunken" (4). s += w; // create a new string "hello drunken world" (5).
s = h
+d
+w; // created one new string for a total of four strings.
var s = "hello " + "drunken " + "world ";
Would assign "hello drunken world" to s.
Each demo tests concatenation with a different type of variable
Concatenating an instance variable (an object property)
Concatenating a local variable of the function.
Concatenating a parameter variable passed to the function.
Note: it is generally bad design practice to modify parameter variables. This is even more true when such variables ore mutable objects (Strings are immutable).
If you ran all three tests above, you probably realized that using a local
variable and concatenating with + (not +=)
is the fastest way to concatenate strings.
Next in this tutorial: Variables