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.

CaffeineAddiction
  • 803
  • 1
  • 14
  • 29
  • Your json is not valid. Use this instead: JSON.parse('{"a":"foo","b":"bar","c":"baz"}'); – friedi Oct 10 '14 at 22:46
  • 1
    Splitting a string should be much faster. See the performance test: http://jsperf.com/splitstringvsjsonparse – friedi Oct 10 '14 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() – xShirase Oct 10 '14 at 22:50
  • possible duplicate of [Splitting string is better or json parse in javascript](http://stackoverflow.com/questions/15615748/splitting-string-is-better-or-json-parse-in-javascript) – Danziger May 29 '15 at 00:19

1 Answers1

0

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"}'

ismnoiet
  • 4,129
  • 24
  • 30
  • 2
    You can't really judge anything from one execution. Make a JSPerf test with thousands of cycles. http://jsperf.com/ – lexicore Oct 10 '14 at 23:29
  • `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. – xaedes Oct 12 '20 at 21:54