Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it counter-productive to pass primitive types by reference? [duplicate]

Tags:

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.

like image 273
user997112 Avatar asked Dec 23 '12 17:12

user997112


People also ask

Are primitive types passed by reference?

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.

Why the distinction between primitive and reference types Why not just have reference types?

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.

How are the primitive types passed?

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.

How do reference types differ from primitive types?

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.


1 Answers

You get the best performance from passing primitive types by value. This is because:

  • primitives are blitable, so the cost of the copy depends on the size
  • primitives are small, only double and long long are bigger than a reference in most environments
  • pass-by-value avoids aliasing, allowing the optimizer to really do its thing

This last point is often overlooked but can make a considerable difference.

like image 198
Ben Voigt Avatar answered Sep 29 '22 11:09

Ben Voigt