While I won't dispute the relative slowness of scripting languages
compared to compiled languages, I must assume you made a typo. 16
minutes?! I copy the script you paste below into a file and run it and
it takes fractions of a second. Possibly benchmarking it for 10^X
iterations will take longer than C, but not by 2 orders of magnitude
(5 seconds to 960 seconds). Probably 5 seconds versus 16 *seconds*
when benchmarked?
I'm too lazy to actually perform the benchmark myself, but felt it
necessary to call this to attention...
Ok, so maybe I'm not that lazy. Just too lazy to write true to life
benchmarks. Here are my "benchmarks". I fixed the C++ version to
include a call to increase (was missing from the version Boris posted,
probably another typo) stuck both of the main bodies in loops to be
run 1000000 times. This is the output from timing them (./test is
test.cc compiled with g++ at default optimization):
$ time ./test.rb
<snip lots of output>
real 2m19.652s
user 0m38.469s
sys 0m16.091s
$ time ./test
<snip lots of output>
real 1m54.417s
user 0m21.358s
sys 0m12.703s
You can see the user time differs by about a factor of 2. The large
real time (which applies to both) is due to the bottleneck of actually
printing to the terminal. I remove that consideration by retiming with
output redirected to /dev/null:
$ time ./test.rb > /dev/null
real 0m25.565s
user 0m21.829s
sys 0m1.393s
$ time ./test > /dev/null
real 0m14.807s
user 0m10.806s
sys 0m1.065s
Again, the difference is about a factor of 2 -- not 192.
Jacob Fugal
Code used in the benchmark:
######### test.rb ##########
#!/usr/bin/ruby
class Base
attr_reader :var
def initialize(v)
@var = v
end
def increase
@var = @var + 1
end
end
class Derived < Base
attr_reader :text
def initialize(x, t)
super(x)
@text = t
end
def append(t)
@text = @text + t
end
end
1000000.times do
d = Derived.new(5, "hallo")
d.increase
print d.var.to_s + "\n"
print d.text + "\n"
d.append("bye")
print d.text + "\n"
end
######### test.cc ##########
#include <iostream>
using namespace std;
class Base {
public:
Base(int x) : var(x)
{}
int getVar() const { return var; }
void increase() { var++; }
private:
int var;
};
class Derived : public Base {
public:
Derived(int x, char* t) : Base(x), text(new string(t))
{}
~Derived()
{
delete text;
}
string* getText() const { return text; }
void append(string* t) {
text->append(*t);
}
private:
string* text;
};
int main (){
for (int i = 0; i < 1000000; i++) {
Derived *d = new Derived(5, "hallo");
d->increase();
cout << d->getVar() << endl;
cout << *d->getText() << endl;
string tmp = "bye";
d->append(&tmp);
cout << *d->getText() << endl;
}
}