Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
Brolls31556yBecause variables tend to be on the stack and pointers require a run off to the heap?
-
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. -
@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. -
@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. -
@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. -
@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.
Related Rants
-
Avyy10This is why one shouldn't code in more than one language a day. Basically spent almost 15 minutes to find out ...
-
ElForritari4Reading academic code is like peering into the disturbed mind of a lunatic...
-
Demolishun17I have been on Reddit... I have been lurking in ProgrammerHumor... I am not proud of these things... I got ...
TIL pointers are slower than normal variables, and it makes a lot of sense, when previously I had thought the opposite.
random
c/c++