I am new to Rust and I have been messing around with it lately. I was curious about the performance of accessing an array with indexes in Rust compared to C.
I made these two programs:
fn main() {
let mut arr: [[i32; 1000]; 1000] = [[0; 1000]; 1000];
for t in 0..1000 {
for i in 0..1000 {
for j in 0..1000 {
arr[i][j] = (i * j) as i32;
}
}
}
}
and in C:
#include <stdlib.h>
#include <string.h>
#define ARRSIZE 1000
int main() {
int ** arr = malloc(sizeof(int*) * ARRSIZE);
int i, j, t;
for (i = 0; i < ARRSIZE; ++i) {
arr[i] = malloc(sizeof(int) * ARRSIZE);
memset((void*) arr[i], 0, sizeof(int) * ARRSIZE);
}
for (t = 0; t < ARRSIZE; ++t) {
for (i = 0; i < ARRSIZE; ++i) {
for (j = 0; j < ARRSIZE; ++j) {
arr[i][j] = i * j;
}
}
}
for (i = 0; i < ARRSIZE; ++i) {
free(arr[i]);
}
free(arr);
}
The idea is to create a 1000x1000 2D array, and iterate over each element 1000 times doing a simple arithmetic operation in each iteration.
The performance gap between the two is big (C version takes almost 3 seconds, Rust version takes 45 seconds). Is this normal, or am I doing something wrong in the Rust version?
Edit: I tried with bounds checking disabled and got the same results.
Thanks.