JSON stringify or string for localStorage (v5)

Revision 5 of this benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
Always use JSON.stringify
function store(key, val) {
  localStorage.setItem(key, JSON.stringify(val));
}

store('num', 1);
store('on', true);
store('name', 'pamela');
store('obj', {'hello': 'world'});
 
ready
Optionally with typeof
function store(key, val) {
  if (typeof val === 'object') {
    localStorage.setItem(key, JSON.stringify(val));
  } else {
    localStorage.setItem(key, val);
  }
}

store('num', 1);
store('on', true);
store('name', 'pamela');
store('obj', {'hello': 'world'});
 
ready
Optionally with param
function store(key, val, isObject) {
  if (isObject) {
    localStorage.setItem(key, JSON.stringify(val));
  } else {
    localStorage.setItem(key, val);
  }
}

store('num', 1);
store('on', true);
store('name', 'pamela');
store('obj', {'hello': 'world'}, true);
 
ready
Optionally with no string csting
function store(key, val, isObject) {
  if (isObject) {
    localStorage.setItem(key, JSON.stringify(val));
  } else {
    localStorage.setItem(key, val);
  }
}

store('num', '1');
store('on', 'true');
store('name', 'pamela');
store('obj', {'hello': 'world'}, true);
 
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.