Path: blob/trunk/third_party/closure/goog/json/json_perf.js
2868 views
// Copyright 2012 The Closure Library Authors. All Rights Reserved.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS-IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314/**15* @fileoverview JSON performance tests.16*/1718goog.provide('goog.jsonPerf');1920goog.require('goog.dom');21goog.require('goog.json');22goog.require('goog.math');23goog.require('goog.string');24goog.require('goog.testing.PerformanceTable');25goog.require('goog.testing.PropertyReplacer');26goog.require('goog.testing.jsunit');2728goog.setTestOnly('goog.jsonPerf');2930var table = new goog.testing.PerformanceTable(goog.dom.getElement('perfTable'));3132var stubs = new goog.testing.PropertyReplacer();3334function tearDown() {35stubs.reset();36}3738function testSerialize() {39var obj = populateObject({}, 50, 4);4041table.run(function() {42var s = JSON.stringify(obj);43}, 'Stringify using JSON.stringify');4445table.run(function() {46var s = goog.json.serialize(obj);47}, 'Stringify using goog.json.serialize');48}4950function testParse() {51var obj = populateObject({}, 50, 4);52var s = JSON.stringify(obj);5354table.run(function() { var o = JSON.parse(s); }, 'Parse using JSON.parse');5556table.run(function() {57var o = goog.json.parse(s);58}, 'Parse using goog.json.parse');5960table.run(function() {61var o = goog.json.unsafeParse(s);62}, 'Parse using goog.json.unsafeParse');63}646566/**67* @param {!Object} obj The object to add properties to.68* @param {number} numProperties The number of properties to add.69* @param {number} depth The depth at which to recursively add properties.70* @return {!Object} The object given in obj (for convenience).71*/72function populateObject(obj, numProperties, depth) {73if (depth == 0) {74return randomLiteral();75}7677// Make an object with a mix of strings, numbers, arrays, objects, booleans78// nulls as children.79for (var i = 0; i < numProperties; i++) {80var bucket = goog.math.randomInt(3);81switch (bucket) {82case 0:83obj[i] = randomLiteral();84break;85case 1:86obj[i] = populateObject({}, numProperties, depth - 1);87break;88case 2:89obj[i] = populateObject([], numProperties, depth - 1);90break;91}92}93return obj;94}959697function randomLiteral() {98var bucket = goog.math.randomInt(3);99switch (bucket) {100case 0:101return goog.string.getRandomString();102case 1:103return Math.random();104case 2:105return Math.random() >= .5;106}107return null;108}109110111