www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - The effect of ref

reply dokutoku <3729541-dokutoku users.noreply.gitlab.com> writes:
Is there a difference in the execution speed and stability when 
executing the program by rewriting the parameter of the function 
argument like this?


```d
void test1 (int * X)
{
	// some processing
}

void test2 (ref int X)
{
	// some processing
}
```
Nov 21 2019
next sibling parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Friday, 22 November 2019 at 03:42:26 UTC, dokutoku wrote:
 Is there a difference in the execution speed and stability when 
 executing the program by rewriting the parameter of the 
 function argument like this?
the generated code the processor sees is generally identical, but the `ref` version is potentially better because then X cannot possibly be `null` which can help you write better code and might help the optimizer too.
Nov 21 2019
parent ketmar <ketmar ketmar.no-ip.org> writes:
Adam D. Ruppe wrote:

 On Friday, 22 November 2019 at 03:42:26 UTC, dokutoku wrote:
 Is there a difference in the execution speed and stability when 
 executing the program by rewriting the parameter of the function 
 argument like this?
the generated code the processor sees is generally identical, but the `ref` version is potentially better because then X cannot possibly be `null` which can help you write better code and might help the optimizer too.
still, using explicit pointers may be good for readability. int a; foo(a); // does it chage `a`? boo(&a); // oh, yeah, now i see that it will prolly change `a` unsafe coding style, but for me pointers for `ref` are more readable.
Nov 21 2019
prev sibling parent mipri <mipri minimaltype.com> writes:
On Friday, 22 November 2019 at 03:42:26 UTC, dokutoku wrote:
 Is there a difference in the execution speed and stability when 
 executing the program by rewriting the parameter of the 
 function argument like this?


 ```d
 void test1 (int * X)
 {
 	// some processing
 }

 void test2 (ref int X)
 {
 	// some processing
 }
 ```
The Compiler Explorer supports D, so it's a good way to ask these questions. https://godbolt.org/z/gnR6Eu int example.test1(int*): mov eax, DWORD PTR [rdi] imul eax, eax add eax, 1 ret int example.test2(ref int): mov eax, DWORD PTR [rdi] imul eax, eax add eax, 1 ret
Nov 21 2019