Thursday, November 7, 2013

Performance comparison between Javascript, python and perl


    One of our projects has heavy processing on json string.  Python was the language of choice, but I was curious on how the other languages perform, so I did a simple comparison against  2 other languages (actually their interpreters): Javascript, Perl.

   We are not surprised that Javascript is the fastest because 1) JSON is a native data format in javascript  2)  we had heard V8 engine (which Node is based on) is the fastest interpreter of all scripting languages.   We know this doesn't mean we have to change our  choice of language to be javascript right away, but it does give some idea how much performance gain we may get.

    Disclaimer:  this is just one test and focus on one type of message processing,   so it's far from being comprehensive.  Don't want to start a war here :-)

Setup

  • CPU:   Intel(R) Core(TM) i3 CPU M 380  @ 2.53GHz
  • OS: Ubuntu 11.04 desktop 64bit
  • Node (for javascript):  v0.4.9
  • Python 2.7.2+,  json module version 2.0.9.
  • Perl 5.12.4,  JSON module version 2.53

Test benchmark


  • Take the following json string, convert it to a object (specific to that language/intepreter under test)
    {"addr": {"city": "austin", "zip": 12345}}
  • replace the "city" field of the object to be "houston"
  • encode the object into json string.
  • do the above 1 million times and measure the total time it takes.

Result

LanguageTime taken
Python17.03s
Javascript (Node)2.85s
Perl4.38s


Here are the code snippets for each of the three languages.

Python

 import time  
 import json  
 import os  
 #purpose: test performance of python.  
 a = '{"addr": {"city": "austin", "zip": 12345}}'  
 ts = time.time()  
 for i in range(0,1000000):  
   x = json.loads(a)  
      x["addr"]["city"] = "houston"  
      y = json.dumps(x);  
 print time.time() - ts  

Javascript

 //==========process a simple json string in nodejs, took 2.845seconds=============  
 a = '{"addr": {"city": "austin", "zip": 12345}}';  
 ts = new Date().getTime()  
 for (i=0; i<1000000; i++) {  
   b = JSON.parse(a);  
      b.addr.city = "houston"  
      JSON.stringify(b);  
 }  
 console.log(new Date().getTime() - ts)  


Perl

 #==========process a simple json string in perl, took 4.377seconds=============  
 use JSON;  
 use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep  
            clock_gettime clock_getres clock_nanosleep clock  
            stat );  
 $json = JSON->new->allow_nonref;  
 $a = '{"addr": {"city": "austin", "zip": 12345}}';  
 $start = getTS();  
 for ($i=0; $i<1000000; $i++) {  
   $b = $json->decode ($a);  
      $b->{addr}->{city} = "houston";  
      $c = $json->encode($b);  
 }  
 print getTS() - $start,"\n";  
 sub getTS {  
      my ($seconds, $microseconds) = gettimeofday;  
      return $seconds + (0.0+ $microseconds)/1000000.0;  
 }  


No comments:

Post a Comment