Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this JavaScript program is faster than C++ to fill a big array?

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?

like image 430
MaiaVictor Avatar asked Jul 27 '26 02:07

MaiaVictor


1 Answers

Try this version

void gen(int w,int h,std::vector<int>& a){
    a.resize(w*h);
    for (int i=0; i<w*h; ++i)
        a[i]=i;
}

int main(){
    for (int i=0; i<100; ++i) {
        std::vector<int> a;
        gen(1000,1000,a);
    }
};

The problem with your version is that it copies the vector when it returns the value. Therefore it's not a direct equivalent to the JS version.

like image 152
john Avatar answered Jul 29 '26 16:07

john