How is pointer incrementation faster than addition in C?
Doing tests like this isn't exactly perfect, there are just way too many factors to consider...and unless you want to get into super nitty gritty details on registers/cache sizes operation size etc the general approach I would say just write good/readable code because little micro-optimizations arent typically needed (and often can be effected by functions and code that had run just prior to it). Also, I mentioned it before but I'll mention it again you shouldn't rely on metrics from running a quick function like this once. There are too many variables that will throw off the measurement.
Now to get onto why func1 and func2 would be different, where is what I would think (I didn't look at your assembly posted because if you need to look at assembly to optimize code the general ask should be is it even worth the time).
func1, you have the memory location str and integer i. Now both of these will be stored; your for loop is incrementing i a nice and simple task
Now your stop condition of str; what is it doing? It's taking the str and adding i*sizeof(char) to it. Now you are effectively doing an additional addition AND multiplication to the loop. Then after that it derefences and check for str != NULL to continue (btw, maybe it's the way I was taught but you should really be adding != NULL or != '\0').
func2, your loop is only adding sizeof(char) to i each iteration.
So for myself I would inherently have assumed func2 without optimizations would run quicker because it boils down to having 1 variable in cache that is being added while func2 requires 2 variables, multiplication and 2 additions.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now