I'm trying to figure out what is the best efficiency wise argument structure to pass to a recursive function.
lets say I have a simple and a useless recursive function in JavaScript, and a variable of type string that holds, I don't know, like 10 000 000 characters
let str;
function test(arg,i){
if(i<1000){
test(arg,i+1);
}
}
now I of course want to use this function and I want to pass the str
variable as an argument.
I thought of two possible ways to pass it:
- simply passing it to the function call like this
test(str,0)
. - passing it inside an array or an object like this
test([str],0)
ortest({string:str})
.
I chose to go with option 2, why? well:
option 1 would create an argument variable and copy the content of str
on each call of test()
, that's why passing a string to a function is called a "pass by value" .
option 2 would pass a reference of [str]
or {string:str}
to each call of test()
which means there would be no copying, so logically, based on my understanding, option 1 should have str.length*n
or str.length*(n-1)
(where n is how many times the function was called) more operations, which means option 1 is a lot less efficient than option 2.
my results : after testing the efficiency of the same example (with more calls) I didn't get any performance difference.
is that because my understanding is wrong?
is it because the function is not using arg
in this example?
is it because the function is simple?
so if anyone that knows how JavaScript or in general programming languages work, or someone that have found a solution for this problem, I would be grateful for your explanation.