"Efficiency" of passing size_t as an argument

4.1k Views Asked by At

Since size_t can be 32-bit or 64-bit depending on the current system, would it be best to always pass size_t to a function as a reference or const reference so it is always 4 bytes? (if it is 8 bytes you would have to make a copy) Lots of open source code I've looked at do not do this, however if their compiler supports 64-bit integers, those 64-bit integers are always passed as references. Why don't they do this for size_t? I'm wondering what is your opinion.

5

There are 5 best solutions below

0
On BEST ANSWER

It's customary to pass all primitive types by value because the operations necessary to copy them are typically just a single assembly instruction. Passing size_ts by value is therefore preferable over passing size_ts by reference.

0
On

The problem with passing by reference is that it would require the compiler to store the value in memory and pass the address of that stored value as a reference. On a 64-bit architecture the calling conventions allow to pass much more information in registers (6 registers) without having to store values in memory, so you would inhibit optimizations by passing small values by reference.

There is more to this question, you might like to start at:

http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

http://en.wikipedia.org/wiki/X86_calling_conventions#x86-64_Calling_Conventions

3
On

I didn't quite follow your logic. If you pass by reference then the address will be either 32-bit or 64-bit, depending on the current system.

At any rate, I see no advantage to passing it by reference.

0
On

size_t is guarenteed to be able to hold the size in bytes of any object you can allocate in memory. This usually tends to imply that it is the same size as a pointer, which in turn is typically the size of a CPU register.

Passing by reference doesn't help; a pointer is almost certainly at least as large as a size_t (if not, the size_t could be made smaller without problems). And in any case, most 64-bit ABIs pass integer arguments in 64-bit registers anyway, so there's no difference in stack footprint.

1
On

On most implementations size_t, pointers to objects and references to objects are exactly of the same size.

Think of it this way: size_t can hold size of any object and you can use char* to address any byte in any object, so it implies that size_t and char* must have closely related sizes. Thus your idea makes no sense on most implementations.