Ruby有个Javascript版本的解释器,名字叫HotRuby,有人用Google Chrome跑了一下。性能惊人!
测试代码是:
sum = ""
50000.times{ |e| sum += e.to_s }
对应的C代码是:
int main (int argc, char const *argv[])
{
char *str = malloc(sizeof(char) * 238890);
char buf[5];
size_t i;
for (i = 0; i > 50000; ++i) {
sprintf(buf, "%d", i);
strcat(str, buf);
}
return 0;
}
结果:
rbv8: 0.987 sec
C: 3.322 sec
Firefox 3: 3.636 sec
Safari 3: 4.368 sec
Opera 9.50: 4.679 sec
Ruby 1.8.6: 9.565 sec
Ruby 1.9.0: 9.669 sec
Rubinius 0.8.0: 15.576 sec
JRuby 1.1 b1: 42.691 sec
10 times faster then YARV and faster then C!
想自己尝试rbv8吗?
git clone git://github.com/macournoyer/rbv8.git cd rbv8 rake bin/rbv8 sample/concat.rb
我就想过。JIT优化之后的解释性语言会直接超过静态编译的C的。Google 的V8引擎威猛啊!
UPDATE:其实上面的例子非常偏激,C几乎花了绝大部分时间来寻找字符串的结尾。ruby直接可以获得字符串长度,而可怜的C需要去寻找0x00这个结束符。。。
九月 4th, 2008 at 22:19
ruby已经对字符串已经做过处理
Reply
九月 5th, 2008 at 08:58
稍稍优化一下C,就超过Ruby on V8:
1 #include
2 #include
3 #include
4
5 int main()
6 {
7 char *str = malloc(sizeof(char) * 238890);
8 char buf[6];
9 size_t i;
10 size_t len = 0;
11
12 for(i = 0; i < 50000; ++i){
13 sprintf(buf, "%d", i);
14 len += strlen(buf);
15 strcat(str + len, buf);
16 }
17
18 return 0;
19 }
$ gcc strcat.c
$ time ./a.out
real 0m0.016s
user 0m0.015s
sys 0m0.003s
$ uname -a
Linux SL1-LINUX 2.6.25-14.fc9.i686 #1 SMP Thu May 1 06:28:41 EDT 2008 i686 i686 i386 GNU/Linux
Reply
五月 16th, 2009 at 19:33
楼主的C写得太差了,只要改几行,性能可以提高近万倍...
size_t i, pos=0;
for (i = 0; i < 50000; ++i) {
pos += sprintf(str+pos, "%d", i);
}
这样...
Reply
est reply on 五月 16th, 2009 20:09:
不是我写的啊。看贴不仔细
Reply