简体   繁体   中英

Javascript is 100 faster than Classical C in simple for loop test, why?

How JavaScript could do much faster than C for the following simple for loop example. It's almost 100 times faster than C after I tested those two codes. How JavaScript do string concatenation faster than C in the loop? Somebody said JavaScript is heavy dynamic language and it change variable, function on run-time, What's that meaning ? From the console.log or printf for str variable, it proved the for-loop is executed in both code without any compiler optimization that I guess.

JavaScript Loop Time: 205ms
C loop time: 32500ms

javascript:

 var i, a, b, c, max,str;
 max = 2e5;
 str="";
 var a = new Date();
 var myvar =   Date.UTC(a.getFullYear(),a.getMonth(),a.getDay(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds());
 for (i=0;i< max;i++) {
     str= str+i+"=";  //just concat string
 }
 var a = new Date();
 var myvar2 = Date.UTC(a.getFullYear(),a.getMonth(),a.getDay(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds());
 console.log("loop time:",myvar2-myvar);  //show for-loop time
 console.log("str:",str);  //for checking the for-loop is executed or not

classical c

#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <time.h>
int main() {
    int i, a, b, c, max;
    clock_t t1, t2;
    t1 = clock();
    max = 2e5;
    char f[9];
    char str[10000000] = {""};
    for (i = 0; i < max; i++) {
        sprintf(f, "%ld", i); // convert integer to string
        strcat(str, "="); // just concat
        strcat(str, f);
    } // just concat
    t2 = clock();
    float diff = (((float)t2 - (float)t1) / 1000000.0F) * 1000;
    printf("loop time output in ms= :%.2fms\n", diff); // show for-loop time
    printf("str:%s\n", str); // check whether the for loop is executed or not
    return 0;
}

Javascript is 100 faster than Classical C in simple for loop test, why?

Because C does not have strings in the same sense javascript has.

To make the test more fair, do these changes:

Outside the loop add

char *strptr;
strptr = str;

and replace the loop with

for (i = 0; i < max; i++) {
    strptr += sprintf(strptr, "=%d", i);
}

Of course now, after these changes, the javascript version may be doing more work than the C version. C has no buffer overflow checks. The javascript version, apparently, is checking the size of the string and expanding it when needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM