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

> Your (1) only affects compilation time, [...]

No, it mostly affects execution time. Whether the effect is meaningful, however, depends on various factors.

> [...] and even this is assuming a particular implementation of arrays (which is not a given).

Eventually, all arrays boil down to pointer+offset memory accesses. Well, if your programming language internally implements "arrays" as hashmaps, then you've already lost performance-wise, of course.

> Why would you need to use "modulo and division into round/ceil/floor" on array offsets?

Whenever you're working with 2D/3D data in manually managed memory.

> How often you do it?

When you're writing web services? Probably not so much. When you're doing image manipulation or 3D graphics? All the time.



> No, it mostly affects execution time.

Citation needed. Yes, the -1 appears in the source code. It might even appear in the intermediate representation. It'll even show up in the assembly for multidimensional arrays (but it'll all get folded into a single `mov` assembly for vectors).

But I dare you to actually demonstrate a performance difference. Compared to a memory access, a `dec` is free.


> No, it mostly affects execution time.

That's what I was thinking, too, but most of the time (even if the index is not static) the -1 can be eliminated by just modifying the address at which the array is assumed to start. That is,

    arr[x]
compiles into an access at address

    (arr - 1) + x
Since the address of arr is statically known, arr - 1 is, too, and the address of "one before the first element" will be what's written as the base for the memory access.


> Since the address of arr is statically known [...]

No, that's almost never the case – only when accessing a static array. Typically, that restricts it to static look-up tables and very simple embedded systems.


At some point I would like to write up a story about this team in my University Object-Oriented Programming class who decided to use 1-based 1ndexes in Java while making a 2-D array for a board game.

I don't want to spoil it, but the following picture of a how they stored a 3x3 tic-tac-toe board is a hint:

  [ null, null, null, null, null, null,

  null, X, 0, X, null, null,

  null, null, O, X, X, null, 

  null, null, null, X, 0, 0 ]


>When you're writing web services? Probably not so much.

I bet it's done a lot as a lot of data structures are implemented vid pow2 length arrays. It's just the people who write them are unaware.




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

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

Search: