Time comparison between delete and assignment

I was wondering how the time taken to free allocated memory compared to an assignment command.

In other words, which of these two would result in the mutex being locked for the shorter amount of time?

eg. (where data, tempData and otherData are pointers)
1
2
3
4
5
6
7
8
Mutex->Lock();
if( data != 0)
{
    delete data;
    data = 0
}
data = otherData;
Mutex->Unlock();

Or
1
2
3
4
5
6
7
8
9
tempData = data;
Mutex->Lock();
data = otherData;
Mutex->Unlock();
if( tempData != 0)
{
    delete tempData;
    tempData = 0
}
Firstly you can delete a null pointer so the first one you could write like this:
1
2
3
4
Mutex->Lock();
delete data;
data = otherData;
Mutex->Unlock();

Secondly delete causes the destructor to be called and that could take some time. Therefore I would suggest your second example is faster.

That could likewise be written:
1
2
3
4
5
tempData = data;
Mutex->Lock();
data = otherData;
Mutex->Unlock();
delete tempData;

I assume there is no need to set tempData to zero as it won't be used by anyone else.
While copy-assignment of a pointer is certainly faster than a memory deallocation and possibly a destructor call, the examples are not equivalent. I am having a hard time coming up with context in which the synchronization in the second example does anything useful.
Thanks Galik, you're right there is no point setting tempData to zero.
Thanks to both of you, I suppose the root question was "Is copy assignemnt faster than memory deallocation?", which it seems it is.
Topic archived. No new replies allowed.