Small code versus performance_
20/12/2024
Chatgpt and other "generative" AIs are now the common choice when you want to "work faster", especially in programming.
Well, sometimes, it does the job and sometimes it doesnt.
Let's ask him to write its own version of some code I use in my npm library (https://www.npmjs.com/package/randomiz)
And don't forget to never ask for performance, because it generally purpose you to change your programming language (valid option but worst possible move).
Here's what I got after a few prompt (a randomized matrix generator):
function randMat(rows,cols,mix,max){ return Array.from( { length: rows },() => Array.from({ length: cols}, () => randInt(mix,max)) ); }
What does that code do (don't take a look at randInt, since it's not very important -> you'll see) ?
Well, it creates an array from an anonymous function that returns itself an array filled of randInt(min,max) value.
Pretty compressed and pro looking, is'nt it?
Well, compared to my code, you'll think that:
function randMat(rows,cols,mix,max){ let l = new Array(rows); for ( var x = 0; x < rows; x++){ l[x] = new Array(cols); for ( var y = 0; y < cols; y++){ l[x][y] = randInt(mix,max); } } return l; }
Mine looks... well, pretty noob.
But what if we compare them on performances?
Well, with only 1 call, you can't really monitor differences (thanks to nodeJS's speed).
With 100'000 calls, and a 20*20 matrix (randMat(20,20,0,255)), I got that:
3500ms for the chatgpt's optmized one, and 550ms for mine. Why?
Well, because the chatgpt's code constructs Arrays with functions returning Arrays, while mine just fills them incrementally (the noob way).
I'm not an expert of JS and V8 (most use JS runtime), but I'm sure that's the difference.
In conclusion... let's say that small code doesn't mean fast, and it's not because you can read it faster that the computer is gonna do it faster too... the old basic for loop is still capable of things you don't know. (except the python one which is iterating a "list" when you call range() :) ).
Have a nice day!