在简单的 for 循环测试中,Javascript 比经典 C 快 100,为什么?

标签 javascript c

对于以下简单的 for 循环示例,JavaScript 如何比 C 执行得更快。在我测试了这两个代码后,它几乎比 C100 倍JavaScript 如何在循环中比 C 更快地进行字符串连接?有人说 JavaScript重型动态语言,它会在运行时更改变量、函数,这是什么意思? 从 console.logprintf for str 变量,证明执行了 for 循环 在这两个代码中,我猜没有任何编译器优化。

JavaScript 循环时间:205 毫秒
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

经典的 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?

因为 C 没有 javascript 所具有的相同意义的字符串。

为了让测试更公平,做这些改变:

在循环外添加

char *strptr;
strptr = str;

并将循环替换为

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

当然现在,在这些变化之后,javascript 版本可能比 C 版本做更多的工作。 C 没有缓冲区溢出检查。显然,javascript 版本正在检查字符串的大小并在需要时扩展它。

关于在简单的 for 循环测试中,Javascript 比经典 C 快 100,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25629012/

相关文章:

javascript - 无序列表的布局

javascript - 放大弹出窗口在数据表的第二页上不起作用

c - C 中的 10000 阶乘

c - 使用指向 int 的指针作为数组索引

javascript - 使用 Javascript 变量设置 Div 样式

javascript - React 中单选卡片

javascript - 如何在带有偏移量的javascript中找到xy位置

c - 在 C 中将未初始化的二维数组作为参数传递

c - 需要 __alignof__ 的调试符号

c - 使用 C 实现哈希表