While reading some of the standard library source code, I have encountered very little use of pointers for function parameters, even with const
, unless that specific parameter is edited by the function. From my perspective, it doesn't seem very efficient as you are making a complete copy of the argument (obviously a shallow copy). So why is this? Is it better than passing something as a constant pointer, or is it just the "idiomatic Zig way"?
Thank you very much.
TL;DR if passed by value, the Zig compiler may still decide to pass by reference under the hood.
from the docs:
Primitive types such as Integers and Floats passed as parameters are copied, and then the copy is available in the function body. This is called "passing by value". Copying a primitive type is essentially free and typically involves nothing more than setting a register.
Structs, unions, and arrays can sometimes be more efficiently passed as a reference, since a copy could be arbitrarily expensive depending on the size. When these types are passed as parameters, Zig may choose to copy and pass by value, or pass by reference, whichever way Zig decides will be faster. This is made possible, in part, by the fact that parameters are immutable.
You can still pass by reference explicitly, and sometimes this is even necessary to prevent undefined behavior - for example in a struct's method, you could want to access data of that struct's instance, not a temporary copy of it which you would get from a pass-by-value. This can become a pitfall if your method returns a pointer.