What is a more efficient way to work with an array of records?

What is more effective?

FUserRecords[I].CurrentInput:=FUserRecords[I].CurrentInput+typedWords; 

or

 var userRec: TUserRec; ... userRec:=FUserRecords[I]; userRec.CurrentInput:=userRec.CurrentInput+typedWords; FUserRecords[I]:=userRec; 
+7
delphi
source share
2 answers

In the described case, the first example will be the most effective.

Entries are value types, so when you do this line:

 userRec:=FUserRecords[I]; 

In fact, you copy the contents of the record in the array to a local variable. And when you do the opposite, you copy the information again. If you iterate over an array, this can be quite slow if your array and records are large enough.

If you want to go down the second path to speed things up, you can manipulate the record in the array directly using the pointer to the record, for example:

 type TUserRec = record CurrentInput: string; end; PUserRec = ^TUserRec; var LUserRec: PUserRec; ... LUserRec := @FUserRecords[I]; LUserRec^.CurrentInput := LUserRec^.CurrentInput + typedWords; 

(as discussed in the comments, carriages (^) are optional. I just added them here for completeness).

Of course, I have to point out that you really only need to do this if there really is a performance problem. It is always useful to profile your application before passing these kinds of optimizations.

EDIT:. Beware of all the discussions on performance that you are looking at, is that if most of your data in records is strings, then most of any performance lost in the example that you have is displayed in string concatenation rather than recording manipulation .

In addition, strings are mainly stored in the record as pointers, so the record will actually be the size of any integers, etc. plus the size of the pointers to the lines. Thus, when you merge with a string, it will not increase the size of the record. You can basically look at the processing part of the lines of your code as a separate issue for write manipulation.

You mentioned in your comments below, this is for storing the input of several keyboards, I can not imagine that you will have more than 5-10 elements in the array. At this size, performing these steps to optimize the code will not really increase the speed much.

I believe that your first example and the code with the pointer above will have approximately the same performance. You must use which is ever the easiest for you to read and understand.

N @

+10
source share

Faster and more readable:

 with FUserRecords[I] do CurrentInput := CurrentInput + typedWords; 
+1
source share

All Articles