C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript program that uses string, length
var animal = "cat";
// Write the string and its length.
document.write(animal + "; " + animal.length);
Output
cat; 3
Tip: Length is constant but only for an object at a point in time. If a local variable changes, the length too changes.
JavaScript program that uses array, length
// Get length of array.
var sizes = [10, 11, 12, 13];
document.write(sizes.length + "; ");
// Push element and get length again.
sizes.push(14);
document.write(sizes.length + "; ");
Output
4; 5;
Program 1: This program calls the length property on a string many times. The length is accessed in the hot part of the loop.
Program 2: The program uses a cached local variable to avoid calling length more than once. It accesses the local in the loop.
Result: In Google Chrome in 2016 the length cache is slightly faster. In a real page, this difference would likely not be noticeable.
JavaScript program that benchmarks length
var x1 = performance.now();
var text = "carrot";
var result = 0;
// Test string length.
for (var i = 0; i < 100000000; i++) {
if (text.length === 6) {
result++;
}
}
var x2 = performance.now();
document.title = (x2 - x1) + "/" + result;
JavaScript program that benchmarks length cache variable
var x1 = performance.now();
var text = "carrot";
var textLength = text.length;
var result = 0;
// Test string length with local cache.
for (var i = 0; i < 100000000; i++) {
if (textLength === 6) {
result++;
}
}
var x2 = performance.now();
document.title = (x2 - x1) + "/" + result;
Output
208 ms access length
201 ms access length cached var