What is call by sharing?
Call by sharing
In programming languages, call by sharing is a hybrid evaluation technique to pass parameters to a function. This technique uses both commonly used evaluation strategies, that is, pass by value for immutable objects and pass by reference for mutable objects. This technique is being adopted by all emerging programming languages like JavaScript, Java, Python, ROR, Julia, and so on, as an evaluation strategy.
Call by value vs. reference vs. sharing
Call by value | Call by reference | Call by sharing |
The main function calls the | The main function calls the | The main function calls the |
The |
| The |
The actual argument remains unchanged. | The actual argument is also changed. | The actual argument remains unchanged if immutable, and changed if mutable. Only the value in |
Simple objects like strings, integers, and floats are immutable objects. Objects like arrays and lists are mutable objects.
int n = 5; is immutable.
int arr[] = [1, 2, 3, 4, 5]; is mutable.
If a simple variable like n is passed as a parameter to the function in the call by sharing technique, the actual variable remains unchanged. However, if an array element arr[0] is passed as a parameter to the function, the changes are reflected in the actual array object.
Code example
var var_value = 5;var var_ref = {val: 5};var var_shr = {val: 5};console.log("value of var_value at start: ", var_value);console.log("value of var_ref at start: ", var_ref.val);console.log("value of var_shr at start: ", var_shr.val);function passValue(var_value_func){var_value_func = 10;}function passRef(var_ref_func){var_ref_func.val = 10;}function passShr(var_shr_func){var_shr_func = {var_shr_func: 10};}console.log("\nAfter applying Evaluation techniques");passValue(var_value);console.log("value of var_value at end: ", var_value);passRef(var_ref);console.log("value of var_ref at end: ", var_ref.val);passShr(var_shr);console.log("value of var_shr at end: ", var_shr.val);
Code example
- Line 8: We define the
passValuefunction to implement the call by value as an evaluation strategy. - Line 11: We define the
passReffunction to implement the call by reference as an evaluation strategy. - Line 14: We define the
passShrfunction to implement the call by sharing as an evaluation strategy. - Line 19: We call the
passValuefunction and passvar_valueas an argument to the function. - Line 22: We call the
passReffunction and passvar_refas an argument to the function. - Line 25: We call the
passShrfunction and passvar_shras an argument to the function.
Free Resources