First commit
[cpp_sandbox.git] / Sandbox / CostOfUsingStatic.cpp
1 #include "CostOfUsingStatic.h"
2
3 #include <iostream>
4 using namespace std;
5
6 // From: https://www.youtube.com/watch?v=B3WWsKFePiM
7
8 namespace CostOfUsingStatic
9 {
10 struct C
11 {
12 // This call is costy.
13 static const string& magic_static()
14 {
15 // Static variables are very costly.
16 // Each time a thread safe comparison must be executed.
17 static const string s = "bob";
18 return s;
19 }
20
21 const string& s = magic_static();
22
23 const string& magic_static_ref()
24 {
25 return s;
26 }
27 };
28 }
29
30 void CostOfUsingStatic::tests()
31 {
32 C c;
33 size_t total_size = 0;
34
35 for (int i = 0; i < 2000000000; ++i)
36 {
37 total_size += c.magic_static_ref().size() + i; // It takes ~500 ms.
38 //total_size += C::magic_static().size() + i; // It takes ~1200 ms.
39 }
40
41 //return total_size;
42
43 cout << "total size: " << total_size << endl;
44 }