10

TIL pointers are slower than normal variables, and it makes a lot of sense, when previously I had thought the opposite.

Comments
  • 4
    Because variables tend to be on the stack and pointers require a run off to the heap?
  • 4
    That can be the case - I guess you mean loading the pointer's content is one load, and then loading the data from the address is a second load.

    On the other hand, a local variable will be loaded via offset to the stack pointer, which is one instruction.

    However, if you have a large struct that you hand down a call chain, then you don't want to pass that by value over the stack and copy it every time. Instead, you hand over a pointer to that struct and mark the referenced data type as const.
  • 0
    @Fast-Nop @Brolls

    From what I read, when you're accessing data from a pointer, you're ALWAYS going to RAM. When you access normal variables, it's quite likely that they will be in a register.

    There was also talk about additional steps going from pointer to data, and someone gave an assembly example. It was indeed extra asm instructions.

    Of course, both things carry small differences when talking about day-to-day usage.

    Interesting nonetheless.
  • 1
    @AlgoRythm no, it will not always go to RAM. It depends on what the aliasing analysis says, which is also a potential rabbit hole of undefined behaviour.

    Also, you can add the "restrict" qualifier to a pointer, which says "nothing can alias this here". That's quite important especially in numerics code where everything is float and aliasable, and "restrict" helped C to catch up somewhat to Fortran in that domain.
  • 0
    @Fast-Nop Not sure how a pointer can't always go to RAM, since a pointer is a pointer to... RAM.

    But sure. Compiler weirdness. Fine. What I said is generally true though, so it isn't fair to call it wrong on some edge case.
  • 2
    @AlgoRythm true, a pointer is to RAM, but it doesn't always go to RAM, which is why you need the volatile qualifier if you want to make sure that it really goes to RAM (and sometimes even a memory fence).

    C isn't assembly, and the abstract C machine model is designed to ideally avoid unnecessary load/store, especially when helped using restrict and const. Of course, with optimisation active.

    Getting the pointer aliasing stuff right is crucial for performance of pointer-heavy code.
  • 0
    Well, yeah. Another read from the pointer address to value
Add Comment