On the development of a language that compiles to JavaScript, I'm considering targeting C++ too, in order to generate faster programs when needed. My plan was to use std::vectors to hold the dynamic arrays of my language. Filling a big array repeatedly will be a normal operation (double buffering), so I've tested that:
#include <iostream>
#include <vector>
std::vector<int> gen(int w,int h){
std::vector<int> a;
a.resize(w*h);
for (int i=0; i<w*h; ++i)
a[i]=i;
return a;
};
int main(){
for (int i=0; i<100; ++i)
std::vector<int> a = gen(1000,1000);
};
Curiously, this program is not faster than the JavaScript equivalent:
gen = function(w,h){
var a = new Float32Array(w*h);
for (var i=0; i<w*h; ++i)
a[i]=i;
return a;
};
for (var i=0; i<100; ++i)
gen(1000,1000);
Surprisingly, the JS version runs 3x faster.
clang++ my_program.cpp -o my_program
time ./my_program
real 0m1.393s
user 0m1.379s
sys 0m0.005s
time node my_program.js
real 0m0.458s
user 0m0.320s
sys 0m0.132s
Why is this happening? Should I reconsider?
resize(). Just instantiate the vector like this:std::vector<int> a(w*h);