1

I have a key value pair containing five keys with values as huge array of thousand objects each . I can either subset it while passing it into a function or i can pass whole array in the function.

For e.g:

keyVal ={"first_array": Object[1000],
"second_array": Object[1000],
"third_array": Object[1000],
"fourth_array": Object[1000]
}
var first_arr = keyVal.first_array

Two possibilities:

function notSubsettedArgs(keyVal){
$.each(keyVal.first_array,function(i,item){
//some processing});
}

function subsettedArgs(first_array){
$.each(first_array,function(i,item){
//do some processing});
}

Does it make difference in javascript ?
Does function takes the load of size of arguments ?
Thanks

igauravsehrawat
  • 3,696
  • 3
  • 33
  • 46

1 Answers1

7

JavaScript passes arrays and objects to functions by passing a copy of the reference to the array/object, so it is likely to be fine to pass the whole thing. Just know that if you mutate it in the function, those changes will affect your original array/object!

If this is browser code and not server (e.g., Node.js) code, you can test with jsperf.com. Just be careful. It's easy to do JS benchmarks wrong!

Trott
  • 66,479
  • 23
  • 173
  • 212
  • *"JavaScript passes arrays and objects to functions by reference"* To be more precise, JavaScript passes everything by *value*, but the value is a reference to an object. That's different from the actual meaning of *pass by reference*. – Felix Kling Apr 28 '15 at 19:16
  • 1
    Thanks. I've tried to make the language more precise: "JavaScript passes arrays and objects to functions by passing a copy of the reference to the array/object" – Trott Apr 28 '15 at 19:20