簡體   English   中英

在簡單的循環測試中,Javascript比Classical C快100,為什么?

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

對於以下簡單的for循環示例, JavaScript如何比C快得多。 在測試這兩個代碼之后,它幾乎比C100倍 JavaScript如何在循環中比C更快地進行字符串連接? 有人說JavaScript重型動態語言 ,它改變了變量,在運行時起作用,這是什么意思? console.logprintf for str變量,它證明了for循環在兩個代碼中執行而沒有任何編譯器優化,我猜。

JavaScript循環時間: 205ms
C循環時間: 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

經典的

#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比Classical C快100,為什么?

因為C沒有javascript所具有的相同意義上的字符串。

為了使測試更公平,請執行以下更改:

在循環之外添加

char *strptr;
strptr = str;

並用。替換循環

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

當然,現在,經過這些更改后,javascript版本可能比C版本做更多的工作。 C沒有緩沖區溢出檢查。 顯然,javascript版本正在檢查字符串的大小並在需要時展開它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM