What is the more efficient way?
FUserRecords[I].CurrentInput:=FUserRecords[I].CurrentInput+typedWords;
or
var userRec: TUserRec;
...
userRec:=FUserRecords[I];
userRec.CurrentInput:=userRec.CurrentInput+typedWords;
FUserRecords[I]:=userRec;
In the case you have described, the first example will be the most efficient.
Records are value types, so when you do this line:
userRec:=FUserRecords[I];
You are in fact copying the contents of the record in the array into the local variable. And when you do the reverse, you are copying the information again. If you are iterating over the array, this can end up being quite slow if your array and the records are quite large.
If you want to go down the second path, to speed things up you can manipulate the record in the array directly using a pointer to the record, like this:
type
TUserRec = record
CurrentInput: string;
end;
PUserRec = ^TUserRec;
var
LUserRec: PUserRec;
...
LUserRec := @FUserRecords[I];
LUserRec^.CurrentInput := LUserRec^.CurrentInput + typedWords;
(as discussed in the comments, the carets (^) are optional. I only added them here for completeness).
Of course I should point out that you really only need to do this if there is in fact a performance problem. It is always good to profile your application before you hand code these sorts of optimisations.
EDIT: One caveat to all the discussion on the performance issue you are looking at is that if most of your data in the records are strings, then most of any performance lost in the example you have shown will be in the string concatenation, not in the record manipulation.
Also, the strings are basically stored in the record as pointers, so the record will actually be the size of any integers etc, plus the size of the pointers for the strings. So, when you concatenate to the string, it will no increase the record size. You can basically look at the string manipulation part of your code as a separate issue to the record manipulation.
You have mentioned in your comments below, this is for storing input from multiple keyboards, I can't imagine that you will have more than 5-10 items in the array. At that size, doing these steps to optimize the code is not really going to boost the speed that much.
I believe that both your first example and the pointer-using code above will end up with approximately the same performance. You should use which ever is the easiest for you to read and understand.
N@
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With