javascriptlocal-storagesessionstorage

Reading localStorage values via indexes


Double your localStorage read performance in Chrome using indexes ls.getItem[i] not keys ls.getItem('key')

Source: this tweet and this talk (slide 19) by some guys that wrote a couple of awesome JavaSciript libraries. I guess these guys know what they are talking about, so I'm wondering why this doesn't work for me:

localStorage.setItem(0, 'Hello world');
localStorage.getItem(0); // 'Hello World' – Works as expected
localStorage.getItem[0]; // undefined

Did I misunderstand something? According to that talk, the last method call should return 'Hello world' not undefined.

They've also linked to this JS Bin, but when reading the values via index there, I still get undefined.

Edit: I know how to properly read the indexes with localStorage, I'm asking about getItem with indexes. It seems the talk just suggests a wrong usage? Also, I wonder why 32 people retweeted that usage, without having tested it. Those things irritate me.


Solution

  • My name is Chris and I am the one responsible for the slide that is causing confusion. For the confusion, I apologize. The slide was somewhat of a joke; allow me to explain..

    In the days leading up to our panel, a tweet was posted and retweeted about doubling your read performance of localStorage. The tweet is the one you referenced (Twitter). However, when I saw this tweet, I did a double take because the syntax looked very wrong to me. I tested the syntax only to discover the same thing that you did: this syntax is clearly not valid if you are trying to access values in localStorage.

    On stage at SXSW, this myth was presented as a joke. Yes, you get double the performance from referencing number indexes on localStorage.getItem. However, all of the values are undefined.

    Anyway, it appears that in the attempt to undo the spread of misinformation, I have managed to spread it further. Thanks for bringing the issue to our attention!