[英]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. 对于以下简单的for循环示例,
JavaScript
如何比C
快得多。 It's almost 100 times faster than C
after I tested those two codes. 在测试这两个代码之后,它几乎比
C
快100倍 。 How JavaScript
do string concatenation faster than C
in the loop? JavaScript
如何在循环中比C
更快地进行字符串连接? Somebody said JavaScript
is heavy dynamic language and it change variable, function on run-time, What's that meaning ? 有人说
JavaScript
是重型动态语言 ,它改变了变量,在运行时起作用,这是什么意思? 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. 从
console.log
或printf
for str变量,它证明了for循环在两个代码中执行而没有任何编译器优化,我猜。
JavaScript Loop Time: 205ms JavaScript循环时间: 205ms
C loop time: 32500ms C循环时间: 32500ms
javascript: 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?
在简单的循环测试中,Javascript比Classical C快100,为什么?
Because C does not have strings in the same sense javascript has. 因为C没有javascript所具有的相同意义上的字符串。
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. 当然,现在,经过这些更改后,javascript版本可能比C版本做更多的工作。 C has no buffer overflow checks.
C没有缓冲区溢出检查。 The javascript version, apparently, is checking the size of the string and expanding it when needed.
显然,javascript版本正在检查字符串的大小并在需要时展开它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.