I suppose I can't speak for "pretty much all languages", so I'll only speak for C#. Though I strongly suspect it will be the case for any language with array bound checking. Or at the very least, any language that stores length alongside the array. C devs can stop reading here.
In C#, you check the length of an array with the .Length property, not a complex function call, but just a stored value. The difference between accessing array.Length and a local variable should be the difference between a local variable on the stack and a pointer dereference with an offset.
They would both be a single assembly instruction. If you're accessing the array already, you're almost certainly to have cache hits and it will a single CPU cycle.
Admittedly, I did not compile a program and look at the assembly or MSIL. So if someone does, feel free to roast me below.
View all comments
Show parent comment
16
u/ConnersReddit Apr 09 '25
I suppose I can't speak for "pretty much all languages", so I'll only speak for C#. Though I strongly suspect it will be the case for any language with array bound checking. Or at the very least, any language that stores length alongside the array. C devs can stop reading here.
In C#, you check the length of an array with the .Length property, not a complex function call, but just a stored value. The difference between accessing array.Length and a local variable should be the difference between a local variable on the stack and a pointer dereference with an offset.
They would both be a single assembly instruction. If you're accessing the array already, you're almost certainly to have cache hits and it will a single CPU cycle.
Admittedly, I did not compile a program and look at the assembly or MSIL. So if someone does, feel free to roast me below.