Possible Duplicate:
Is it better to pass by value or by reference for basic datatypes?
Reasons to not pass simple types by reference?
I did some testing where I had two scenarios, each with two identical functions- one passing the parameter by reference and the other by value. The scenario with strings showed a massive performance increase (because a copy of string is made, calling a constructor) whereas the test with long didn't show any performance increase when passing the value by reference. In fact, sometimes the performance was worse.
Is this expected with primitive types? Is there no point passing them by reference?
I was expecting a copy of a primitive type is made when not using by reference and therefore expected a small performance-boost.
Objects are passed by reference and primitive types are passed by value. A correct statement would be: Object references are passed by value, as are primitive types. Thus, Java passes by value, not by reference, in all cases.
Reference variables are not pointers but a handle to the object which is created in heap memory. The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value.
Passing primitive types in function: Primitive types are always passed by value. These are immutable. This means that even if we change the value in the function, the original value will not change. There are a total of five primitive data types in JavaScript.
Primitive types are the basic types of data: byte , short , int , long , float , double , boolean , char . Primitive variables store primitive values. Reference types are any instantiable class as well as arrays: String , Scanner , Random , Die , int[] , String[] , etc.
You get the best performance from passing primitive types by value. This is because:
double
and long long
are bigger than a reference in most environmentsThis last point is often overlooked but can make a considerable difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With