对于以下简单的 for 循环示例,JavaScript
如何比 C
执行得更快。在我测试了这两个代码后,它几乎比 C
快 100 倍。 JavaScript
如何在循环中比 C
更快地进行字符串连接?有人说 JavaScript
是重型动态语言,它会在运行时更改变量、函数,这是什么意思?
从 console.log
或 printf
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/