The ECMAScript Standard ECMA-262 (6th Edition, June 2015) says
6.1.4 The String Type
The String type is the set of all ordered sequences of zero or more 16-bit unsigned integer values ("elements") up to a maximum length of 253-1 elements.
So don't plan on using more than 9,007,199,254,740,991 or about 9 quadrillion characters. Of course, you should be prepared for systems which cannot allocate 18 PB chunks of memory, as this is not required for conforming ECMAScript implementations.
Answer from Charles on Stack OverflowThe ECMAScript Standard ECMA-262 (6th Edition, June 2015) says
6.1.4 The String Type
The String type is the set of all ordered sequences of zero or more 16-bit unsigned integer values ("elements") up to a maximum length of 253-1 elements.
So don't plan on using more than 9,007,199,254,740,991 or about 9 quadrillion characters. Of course, you should be prepared for systems which cannot allocate 18 PB chunks of memory, as this is not required for conforming ECMAScript implementations.
I think the question is asking about the practical limit, not the spec limit. And, no, it is not always the amount of RAM you have. I have x86_64 24GB PC running Linux Mint with x86_64 Firefox and x86_64 Chrome, and the limits I ran into were:
- 1,073,741,822 limit in Firefox 84
- 536,870,888 limit in Chrome 87
Any higher and Firefox throws a Uncaught RangeError: repeat count must be less than infinity and not overflow maximum string size, whereas Chrome throws Uncaught RangeError: Invalid string length. Use the following snippet to run a binary search for the max string length in your browser:
for (var startPow2 = 1; startPow2 < 9007199254740992; startPow2 *= 2)
try {" ".repeat(startPow2);} catch(e) {
break;
}
var floor = Math.floor, mask = floor(startPow2 / 2);
while (startPow2 = floor(startPow2 / 2))
try {
" ".repeat(mask + startPow2);
mask += startPow2; // the previous statement succeeded
} catch(e) {}
console.log("The max string length for this browser is " + mask);
Videos
Characters are stored on 16 bits
When you see that 256*2**20 characters are in a string, that does not mean that 256 megabytes of memory is allocated. JavaScript stores every character on two bytes (as it is utf16 encoded by the specification).
A word about ropes
Todays browsers (even IE) store strings in an advanced way, most often using a rope datastructure.
- Ropes do not need a coherent memory region to be allocated
- Can even deduplicate substrings, that means
s+sdoes not necessarily use twice the memory ass - Concatenation is very fast
- Element access is a bit slower
By examining some runs in IE and Chrome, I would say that both of them use some lazy evaluation for strings, and will try to expand them occasionally. After running the following snippet, none of the browsers used more memory than before. But if I tried to manipulate the stored window.LONGEST_STRING in the console, IE throw an out of memory error, and chrome froze for a short time, and consumed a lot of memory (>2 GB).
ps: On my laptop IE11 had a maximum string size of 4 GB, Chrome had 512 MB
Browser behaviour
IE11

Chrome47

A faster algorithm to determine max string size
Copyvar real_console_log = console.log;
console.log = function(x) {
real_console_log.apply(console, arguments);
var d = document,b=d.body,p=d.createElement('pre');
p.style.margin = "0";
p.appendChild(d.createTextNode(''+x));
b.appendChild(p);
window.scrollTo(0, b.scrollHeight);
};
function alloc(x) {
if (x < 1) return '';
var halfi = Math.floor(x/2);
var half = alloc(halfi);
return 2*halfi < x ? half + half + 'a' : half + half;
}
function test(x) {
try {
return alloc(x);
} catch (e) {
return null;
}
}
function binsearch(predicateGreaterThan, min, max) {
while (max > min) {
var mid = Math.floor((max + min) / 2);
var val = predicateGreaterThan(mid);
if (val) {
min = mid + 1;
} else {
max = mid;
}
}
return max;
}
var maxStrLen = binsearch(test, 10, Math.pow(2, 52)) - 1;
console.log('Max string length is:');
console.log(maxStrLen + ' characters');
console.log(2*maxStrLen + ' bytes');
console.log(2*maxStrLen/1024/1024 + ' megabytes');
console.log('');
console.log('Store longest string');
window.LONGEST_STRING = alloc(maxStrLen);
console.log('Try to read first char');
console.log(window.LONGEST_STRING.charAt(0));
console.log('Try to read last char');
console.log(window.LONGEST_STRING.charAt(maxStrLen - 1));
console.log('Try to read length');
console.log(window.LONGEST_STRING.length);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
A bug report for the chromium tracker has this comment:
Copy... When allocation fails, we create a
Failure pointer encoding the amount requested, as well as some tag and
type bits. This puts a limit on the maximally possible allocation
request in 32-bit versions of 2^27-1. The maximal flat string length is
~2^28 (512MB space), and the maximal string length is 2^29-1...
Note that this is from 2009, so I imagine that this still has consequences in current versions of V8 as the previous link is in regard to a NodeJS tool running into limits of toString().
Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.
var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
Copying Will's comment into an answer, because I found it useful:
var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ?
string.substring(0, length - 3) + "..." :
string;
Thanks Will.
And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)
I have researched this a bit.
MDN is silent on the issue, and so is the spec (ES5, ES6). They only state that the property accessor must be a string, without any qualifications – in other words, there is no limit as far as the spec is concerned. That's hardly surprising.
How browsers handle it, is another matter. I have set up a test and run it in a number of browsers. Chrome 40 (Desktop), Chrome 40 (Android 5.1), Firefox 36, Opera 27, and IE9+ can deal with a property name of up to 227 characters. Safari 8 (OS X Yosemite) can even handle property names of 230 characters.
For all those browsers except IE, the maximum property length is the same as the maximum string length. IE9+ can handle a maximum string length of ~230 characters, but the limit for object keys is at 227 characters, just as in the other browsers.
The test didn't work in IE8 and Safari on iOS, presumably due to memory issues caused by the test code.
In a nutshell, it is safe to use long property names, even when taking it to extremes. As long as the strings themselves stay within the limits of what browsers can handle, you can use them as property names as well.
No, there is no limit for the string length (as long as it fits into memory), and your implementation seems okay too. It's acutally quite common to have those 'turned around' arrays with e.g. boolean values. And as to the strings as keys: The strings are immutable symbols that are stored at a certain address, and what's actually used as the index for the array is that address (aka pointer aka reference) and not the string itself.