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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
|
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <chrono>
#include <algorithm>
// 性能测试
class PerformanceTest
{
public:
static void stringParameterTest()
{
std::cout << "=== String Parameter Performance Test ===" << std::endl;
const int iterations = 100000;
std::vector<std::string> testStrings;
// 准备测试数据
for (int i = 0; i < 1000; ++i)
{
testStrings.push_back("Test string number " + std::to_string(i));
}
// 测试const std::string&参数
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < iterations; ++i)
{
processWithString(testStrings[i % testStrings.size()]);
}
auto end = std::chrono::high_resolution_clock::now();
auto stringTime = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
// 测试string_view参数
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < iterations; ++i)
{
processWithStringView(testStrings[i % testStrings.size()]);
}
end = std::chrono::high_resolution_clock::now();
auto stringViewTime = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "const std::string& parameter: " << stringTime.count() << " microseconds" << std::endl;
std::cout << "string_view parameter: " << stringViewTime.count() << " microseconds" << std::endl;
std::cout << "Speedup: " << (double)stringTime.count() / stringViewTime.count() << "x" << std::endl;
}
static void substringTest()
{
std::cout << "\n=== Substring Performance Test ===" << std::endl;
const int iterations = 100000;
std::string largeString(1000, 'x');
largeString += "target substring here";
largeString += std::string(1000, 'y');
// 测试string::substr
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < iterations; ++i)
{
volatile auto sub = largeString.substr(1000, 22);
}
auto end = std::chrono::high_resolution_clock::now();
auto stringSubstrTime = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
// 测试string_view::substr
std::string_view sv = largeString;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < iterations; ++i)
{
volatile auto sub = sv.substr(1000, 22);
}
end = std::chrono::high_resolution_clock::now();
auto stringViewSubstrTime = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "string::substr: " << stringSubstrTime.count() << " microseconds" << std::endl;
std::cout << "string_view::substr: " << stringViewSubstrTime.count() << " microseconds" << std::endl;
std::cout << "Speedup: " << (double)stringSubstrTime.count() / stringViewSubstrTime.count() << "x" << std::endl;
}
private:
static void processWithString(const std::string& str)
{
volatile size_t len = str.length();
}
static void processWithStringView(std::string_view str)
{
volatile size_t len = str.length();
}
};
// 实际应用:日志解析器
class LogParser
{
public:
struct LogEntry
{
std::string_view timestamp;
std::string_view level;
std::string_view message;
};
static LogEntry parseLine(std::string_view line)
{
LogEntry entry;
// 查找第一个空格(时间戳结束)
auto firstSpace = line.find(' ');
if (firstSpace != std::string_view::npos)
{
entry.timestamp = line.substr(0, firstSpace);
line.remove_prefix(firstSpace + 1);
// 查找第二个空格(级别结束)
auto secondSpace = line.find(' ');
if (secondSpace != std::string_view::npos)
{
entry.level = line.substr(0, secondSpace);
entry.message = line.substr(secondSpace + 1);
}
}
return entry;
}
static std::vector<LogEntry> parseLog(std::string_view logContent)
{
std::vector<LogEntry> entries;
size_t start = 0;
while (start < logContent.size())
{
auto end = logContent.find('\n', start);
if (end == std::string_view::npos)
{
end = logContent.size();
}
auto line = logContent.substr(start, end - start);
if (!line.empty())
{
entries.push_back(parseLine(line));
}
start = end + 1;
}
return entries;
}
};
// 实际应用:CSV解析器
class CSVParser
{
public:
static std::vector<std::vector<std::string_view>> parseCSV(std::string_view csvContent)
{
std::vector<std::vector<std::string_view>> rows;
size_t lineStart = 0;
while (lineStart < csvContent.size())
{
auto lineEnd = csvContent.find('\n', lineStart);
if (lineEnd == std::string_view::npos)
{
lineEnd = csvContent.size();
}
auto line = csvContent.substr(lineStart, lineEnd - lineStart);
if (!line.empty())
{
rows.push_back(parseCSVLine(line));
}
lineStart = lineEnd + 1;
}
return rows;
}
private:
static std::vector<std::string_view> parseCSVLine(std::string_view line)
{
std::vector<std::string_view> fields;
size_t start = 0;
while (start < line.size())
{
auto end = line.find(',', start);
if (end == std::string_view::npos)
{
end = line.size();
}
auto field = line.substr(start, end - start);
// 简单的引号处理
if (!field.empty() && field.front() == '"' && field.back() == '"')
{
field.remove_prefix(1);
field.remove_suffix(1);
}
fields.push_back(field);
start = end + 1;
}
return fields;
}
};
void PracticalApplicationsDemo()
{
std::cout << "=== Practical Applications Demo ===" << std::endl;
// 日志解析示例
std::cout << "1. Log Parser:" << std::endl;
std::string logData =
"2023-10-01T10:30:00 INFO Application started\n"
"2023-10-01T10:30:01 DEBUG Loading configuration\n"
"2023-10-01T10:30:02 WARN Configuration file not found, using defaults\n"
"2023-10-01T10:30:03 ERROR Failed to connect to database\n"
"2023-10-01T10:30:04 INFO Retrying database connection\n";
auto logEntries = LogParser::parseLog(logData);
for (const auto& entry : logEntries)
{
std::cout << " [" << entry.timestamp << "] "
<< entry.level << ": " << entry.message << std::endl;
}
// CSV解析示例
std::cout << "\n2. CSV Parser:" << std::endl;
std::string csvData =
"Name,Age,City\n"
"\"John Doe\",30,\"New York\"\n"
"Jane Smith,25,London\n"
"Bob Johnson,35,\"Los Angeles\"\n";
auto csvRows = CSVParser::parseCSV(csvData);
for (size_t i = 0; i < csvRows.size(); ++i)
{
std::cout << " Row " << i << ": ";
for (size_t j = 0; j < csvRows[i].size(); ++j)
{
if (j > 0) std::cout << ", ";
std::cout << "'" << csvRows[i][j] << "'";
}
std::cout << std::endl;
}
// 文本分析示例
std::cout << "\n3. Text Analysis:" << std::endl;
std::string text = "The quick brown fox jumps over the lazy dog. "
"This sentence contains every letter of the alphabet.";
std::string_view textView = text;
// 统计单词
size_t wordCount = 0;
size_t start = 0;
while (start < textView.size())
{
// 跳过空白字符
while (start < textView.size() && std::isspace(textView[start]))
{
start++;
}
if (start < textView.size())
{
// 找到单词结束
size_t end = start;
while (end < textView.size() && !std::isspace(textView[end]) &&
textView[end] != '.' && textView[end] != ',')
{
end++;
}
if (end > start)
{
wordCount++;
auto word = textView.substr(start, end - start);
if (wordCount <= 5) // 只显示前5个单词
{
std::cout << " Word " << wordCount << ": '" << word << "'" << std::endl;
}
}
start = end;
}
}
std::cout << " Total words: " << wordCount << std::endl;
std::cout << " Text length: " << textView.length() << " characters" << std::endl;
}
int main()
{
PerformanceTest::stringParameterTest();
PerformanceTest::substringTest();
PracticalApplicationsDemo();
return 0;
}
|