I am in the process of optimizing an arbitrary precision integer class in Xojo and have determined that vast vast majority of the time was being spent creating and destroying class objects. I am refactoring to code to maximize the reuse of class objects and memory blocks and have already cut the processing time by more than 50%. But in the process of doing this I have run into something I can’t explain and maybe someone with a better understanding of Xojo internals can provide some insight.
An arbitrary precision object in my class has three properties:
Name Type Meaning
sign Int64 sign of integer (-1 for negative, 0 for zero, 1 for positive)
digits mutablememoryblock holds the bits of the integer, concatenation of unsigned 64 bit words
used Int64 how many 64 bits words in memoryblock is currently in use
The default constructor sets the sign value and used value to zero and does not create the memoryblock (i.e. a zero value).
Now in my pursuit of maximizing the reuse of objects I am trying to create a fast copy method when two objects already exist. In other words copy objA to objB. So I thought that the best way to do this would be to do the following which overwrites the second object:
objB.sign = objA.sign
objB.used = objA.used
if objA.sign <> 0 then
objB.digits = New xojo.core.mutablememoryblock(objA.digits)
end if
But using a copy like the above slowed the application to an absolute crawl. The normal copy method does the following which creates a new object:
objB = new object ’ call default constructor that sets sign=0 and used=0
objB.sign = objA.sign
objB.used = objA.used
if objA.sign <> 0 then
objB.digits = New xojo.core.mutablememoryblock(objA.digits)
end if
What I am scratching my head about is why is it much faster to create a new object and copy the properties to it than it is to replace the properties of an already existing object. I have not done specific timing, but it looks like the difference is a couple of orders of magnitude or more! My only explanation is that it must be much faster to create a new object and new memoryblock that it is to replace a memoryblock of an existing object. But why would that be the case??