Cpp.js
Bind C++ code to JS on the web and React Native without writing any extra code.
- npm
- pnpm
- yarn
- bun
npm create cpp.js@latest
pnpm create cpp.js@latest
yarn create cpp.js@latest
bun create cpp.js@latest
- C++ & JS using cpp.js
- Only JS
- Try it in your browser
/src/index.js
import { initCppJs } './native/Matrix.h';
const { Matrix } = await initCppJs();
const a = new Matrix(1210000, 1);
const b = new Matrix(1210000, 2);
const result = a.multiple(b);
console.log(result); // execution time: 0.872s
/src/native/Matrix.h
class Matrix : public std::vector<int> {
public:
Matrix(int size, int v) : std::vector<int>(size, v) {}
int get(int i) { return this->at(i); }
std::shared_ptr<Matrix> multiple(std::shared_ptr<Matrix> b) {
int size = sqrt(this->size());
auto result = std::make_shared<Matrix>(this->size(), 0);
for (int i = 0; i < size; i += 1) {
for (int j = 0; j < size; j += 1) {
for (int k = 0; k < size; k += 1) {
(*result)[i*size+j]+=this->at(i*size+k)*(*b)[k*size+j];
}
}
}
return result;
}
};
/src/index.js
import { Matrix } from './Matrix.js';
const a = new Matrix(1210000, 1);
const b = new Matrix(1210000, 2);
const result = a.multiple(b);
console.log(result); // execution time: 5.886s
/src/Matrix.js
export class Matrix extends Array {
constructor(size, v) { super(size); this.fill(v); }
get(i) { return this[i]; }
multiple(otherMatrix) {
const size = Math.sqrt(this.length);
const result = new Matrix(this.length, 0);
for (let i = 0; i < size; i += 1) {
for (let j = 0; j < size; j += 1) {
for (let k = 0; k < size; k += 1) {
result[i*size+j]+=this[i*size+k]*otherMatrix[k*size+j];
}
}
}
return result;
}
}