javascriptandroidandroid-webviewjavascript-objects

Is there a limit on length of the key (string) in JS object?


So we had a case where we would have an object, where key is id (int) and the value is the string. But we noticed that most of the times, we look up id based on the string, so we decided to reverse it and make a string the key and the value is the id. Because that way instead of going through each item and compare values, we could just do var id = storage[text];. Below are the examples of what we did.

Here's the example of the old implementation:

var storage = {
  0 : null,
  1 : "Hello",
  2 : "world!",
  3 : "How are you?"
}

Here's the example of the new implementation:

var storage = {
  "null" : 0,
  "Hello" : 1,
  "world!" : 2,
  "How are you?" : 3
}

I understand that now the string is the key and it's ok to get the same id for the same strings. But since now the string can be potentially pretty huge (slim chance, but probably max 1KB per string), is there a length limit JS or Android webview puts on the object keys?

And also, does this implementation have disadvantages? I haven't noticed any issues so far, but you never know.


Solution

  • 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.