Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Yes, but "human-focused" 1-based indexing comes at a cost since at the end of the day the CPU has to add (index * element-size) to the array base address to get the address of the indexed element. With a 1-based index there's additional overhead in either having to subtract 1 from the index or to have a wasted "element 0" to avoid the need to do that.


I assure you, that if we counted from zero, there would be an instruction to add and multiply in the same number of cycles as a multiply.


That's not possible - the subtract and multiply need to be consecutive (adjust index before multiply by element size), so even if it was a single instruction it would still take longer than a multiply that didn't have to wait for a preceding subtraction.

The only way to avoid the speed penalty would be either to have a wasted element at offset 0, or to maintain the array base address as (address - (1 * element-size)) to avoid having to subtract 1 from the index when accessing. In the latter case for dynamically allocated arrays the code would still have to do a subtraction to adjust the pointer returned by the memory allocator, but at least that would be a 1-time penalty rather than per-element-access.

Of course this is supposing a high level language where an array is abstraction, not one explicity aliased to a chunk of memory such as C where an array and a pointer to it's first element are interchangeable.


That goes against my intuition. Multiplication in hardware to this day relies on addition. Is one adder going to add an extra cycle? Or would that time be amortized? Take a look at slides 45-46 here. https://acg.cis.upenn.edu/milom/cis371-Spring08/lectures/04_...

Do you know the answer to that question? (I don't, but if someone does, it will settle this issue).


I don't know, but looking at that 3-input add makes me think you may be right and the extra addition/subtraction could perhaps be combined into the multiplication.

OTOH, for arrays who's contents are size 2^n (char, short, int, long) I'm sure the generated code isn't using multiply in the first place.

Anyways, an optimizing compiler could certainly remove much of any overhead added by 1-based indexing .. for an array access in a for loop it could, if necessary, calculate the "base-1" address once at start of loop.

Personally, having grown up with assembler and C, and still using C++ today, I'm quite happy with 0-based.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: