string method clear

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void main()
{
	int i;
	DWORD count,stop;
	
	wstring str;

	count=GetTickCount();
	for (i=0;i<1000000; i++)
	{	
		str.append(L"asdfgasdfgasdfgasdfg");// add some random text
		str=L"";
	}

	stop=GetTickCount()-count;
	cout<<"for = "<<stop<<endl;

	count=GetTickCount();
	for (i=0;i<1000000; i++)
	{	
		str.append(L"asdfgasdfgasdfgasdfg");
		str.clear();
	}

	stop=GetTickCount()-count;
	cout<<"for clear() "<<stop<<endl;
}


results for this code

1st run
for = 422
for clear() 3478

2nd run
for = 452
for clear() 3588

3rd run
for = 468
for clear() 3400

It's clear for me that using the =L"" to empty the string is faster.
Why did they made that method, or is it doing something that the =L""; isn't doing?
MinGW:
for = 454
for clear() 375


With optimizations:
for = 172
for clear() 125


VC++:
for = 359
for clear() 3859


With optimizations:
for = 187
for clear() 282


EDIT: Because I wasn't sure the optimizations weren't generating empty loops, I modified the program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>
#include <windows.h>

int main(){
	int i;
	DWORD count,stop;
	
	std::wstring str,
		s2;

	count=GetTickCount();
	const wchar_t *t=L"asdfgasdfgasdfgasdfg";
	for (i=0;i<1000000; i++){
		str.append(t);
		s2.append(str);
		str=L"";
	}

	stop=GetTickCount()-count;
	std::cout<<"for = "<<stop<<std::endl;

	count=GetTickCount();
	for (i=0;i<1000000; i++){
		str.append(t);
		s2.append(str);
		str.clear();
	}

	stop=GetTickCount()-count;
	std::cout<<"for clear() "<<stop<<std::endl;
	return 0;
}

The results are:
MinGW: Both loops average at 359 ms.
VC++: Both loops average at 453 ms.

EDIT 2: I still wasn't sure the loops were fair, so I swapped them. This time, MinGW gave slightly faster times for clear(). Around 50 ms. VC++ gave better times for operator=(). Around 150 ms.
Last edited on
Running your code gives me this results:

for = 1061
for clear() 4102

for = 1076
for clear() 4150


The s2.append(str) is uselss, and it slows the speed. And it is using a lot of memory too, because you never empty it so it will have 2.000.000 * 20 * 2= 80.000.000 bytes = ~76.29 MB.

But I don't get it how you get those values. this works slower for me. And even with the string already stored in a const wchar_t *, it gives me the same values as I had before changing the code. I really don't get it.
Topic archived. No new replies allowed.