0

I am currently working with zeroMQ in Node.js. ZeroMQ allows for message passing between applications in the form of strings. The application will be processing hundreds of thousands of messages.

Would it be faster to parse a delimited String:

"foo bar baz".split(' ');

or a stringified JSON object:

JSON.parse('{"a":"foo","b":"bar","c":"baz"}');

How would one go about testing the efficiency of each (speed & memory) in Node.js and / or in the Browser.

4
  • Your json is not valid. Use this instead: JSON.parse('{"a":"foo","b":"bar","c":"baz"}'); Commented Oct 10, 2014 at 22:46
  • 1
    Splitting a string should be much faster. See the performance test: jsperf.com/splitstringvsjsonparse Commented Oct 10, 2014 at 22:47
  • Splitting a string would give an array, and JSON.parse an object. It's a bit like comparing apples and oranges. If you need an object, use JSON.parse() if not, use split() Commented Oct 10, 2014 at 22:50
  • possible duplicate of Splitting string is better or json parse in javascript Commented May 29, 2015 at 0:19

1 Answer 1

1

to test the required time to execute any instruction in the browser (assuming you have chrome or chromium for Linux ) you can use the something similar to the following code :

// first open the inspector **ctrl+shift+i** then switch to the console tab to write the code 
// or you can go to `tools > developer tools` then choose the console tab 
// here is the code : 


console.time('t1');
"foo bar baz".split(' ');
console.timeEnd('t1'); 

// result t1: 0.020ms 


console.time('t2');
// you instructions here
JSON.parse('{"a":"foo","b":"bar","c":"baz"}');
console.timeEnd('t2');

// result t2: 0.046ms

it is clear that the first way is faster than the second way

note : to convert object string to JSON format you have to put both property and its value within ""

for example in our case :

a:"foo" should be "a":"foo"

b:"bar" should be "b":"bar" and so on

so the entire string ('{a:"foo",b:"bar",c:"baz"}' in the second way ) should be '{"a":"foo","b":"bar","c":"baz"}'

Sign up to request clarification or add additional context in comments.

2 Comments

You can't really judge anything from one execution. Make a JSPerf test with thousands of cycles. jsperf.com
console.time("t1");for(var i=0;i<1000000;++i) { "foo bar baz".split(" "); } console.timeEnd("t1"); Gives me ~100ms. console.time("t2");for(var i=0;i<1000000;++i) { JSON.parse('["foo","bar","baz"]'); } console.timeEnd("t2"); gives me around ~350ms. split seems faster. Array.join is ~85ms, JSON.stringify ~240ms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.