1 | \chapter{String}
|
---|
2 |
|
---|
3 | \vspace*{-20pt}
|
---|
4 | This chapter presents my work on designing and building a modern string type in \CFA.
|
---|
5 | The discussion starts with an overview of the string API, then a number of interesting string problems, followed by how these issues are resolved in this work.
|
---|
6 |
|
---|
7 |
|
---|
8 | \section{String Operations}
|
---|
9 |
|
---|
10 | % https://en.wikipedia.org/wiki/Comparison_of_programming_languages_(string_functions)
|
---|
11 |
|
---|
12 | \VRef[Figure]{f:StrApiCompare} shows a general comparison of string APIs for C, \CC, Java and \CFA.
|
---|
13 | It provides a classic ``cheat sheet'', summarizing the names of the most-common closely-equivalent operations.
|
---|
14 | The over-arching commonality is that operations work on groups of characters for assigning, copying, scanning, and updating.
|
---|
15 |
|
---|
16 | \begin{figure}[h]
|
---|
17 | \begin{cquote}
|
---|
18 | \begin{tabular}{@{}l|l|l|l@{}}
|
---|
19 | C @char [ ]@ & \CC @string@ & Java @String@ & \CFA @string@ \\
|
---|
20 | \hline
|
---|
21 | @strcpy@, @strncpy@ & @=@ & @=@ & @=@ \\
|
---|
22 | @strcat@, @strncat@ & @+@, @+=@ & @+@, @+=@ & @+@, @+=@ \\
|
---|
23 | @strcmp@, @strncmp@ & @==@, @!=@, @<@, @<=@, @>@, @>=@
|
---|
24 | & @equals@, @compareTo@
|
---|
25 | & @==@, @!=@, @<@, @<=@, @>@, @>=@ \\
|
---|
26 | @strlen@ & @length@, @size@ & @length@ & @size@ \\
|
---|
27 | @[ ]@ & @[ ]@ & @charAt@ & @[ ]@ \\
|
---|
28 | @strncpy@ & @substr@ & @substring@ & @( )@, on RHS of @=@ \\
|
---|
29 | @strncpy@ & @replace@ & @replace@ & @( )@, on LHS of @=@ \\
|
---|
30 | @strstr@ & @find@ & @indexOf@ & @find@ \\
|
---|
31 | @strcspn@ & @find_first_of@ & @matches@ & @include@ \\
|
---|
32 | @strspn@ & @find_first_not_of@ & @matches@ & @exclude@ \\
|
---|
33 | N/A & @c_str@, @data@ & N/A & @strcpy@, @strncpy@ \\
|
---|
34 | \end{tabular}
|
---|
35 | \end{cquote}
|
---|
36 | \caption{Language comparison of string API}
|
---|
37 | \label{f:StrApiCompare}
|
---|
38 | \end{figure}
|
---|
39 |
|
---|
40 | As mentioned in \VRef{s:String}, a C string uses null termination rather than a length, which leads to explicit storage management;
|
---|
41 | hence, most of its group operations are error prone and expensive due to copying.
|
---|
42 | Most high-level string libraries use a separate length field and specialized storage management to implement group operations.
|
---|
43 | Interestingly, \CC strings retain null termination in case it is needed to interface with C library functions.
|
---|
44 | \begin{cfa}
|
---|
45 | int open( @const char * pathname@, int flags );
|
---|
46 | string fname{ "test.cc" );
|
---|
47 | open( fname.@c_str()@, O_RDONLY ); // null terminated value of string
|
---|
48 | \end{cfa}
|
---|
49 | Here, the \CC @c_str@ function does not create a new null-terminated C string from the \CC string, as that requires passing ownership of the C string to the caller for eventual deletion.\footnote{
|
---|
50 | C functions like \lstinline{strdup} do return allocated storage that must be freed by the caller.}
|
---|
51 | % Instead, each \CC string is null terminated just in case it might be needed for this purpose.
|
---|
52 | Providing this backwards compatibility with C has a ubiquitous performance and storage cost.
|
---|
53 |
|
---|
54 |
|
---|
55 | \section{\CFA \lstinline{string} Type}
|
---|
56 | \label{s:stringType}
|
---|
57 |
|
---|
58 | The \CFA string type is for manipulation of dynamically-sized character-strings versus C @char *@ type for manipulation of statically-sized null-terminated character-strings.
|
---|
59 | Hence, the amount of storage for a \CFA string changes dynamically at runtime to fit the string size, whereas the amount of storage for a C string is fixed at compile time.
|
---|
60 | As a result, a @string@ declaration does not specify a maximum length, where a C string must.
|
---|
61 | The maximum storage for a \CFA @string@ value is @size_t@ characters, which is $2^{32}$ or $2^{64}$ respectively.
|
---|
62 | A \CFA string manages its length separately from the string, so there is no null (@'\0'@) terminating value at the end of a string value.
|
---|
63 | Hence, a \CFA string cannot be passed to a C string manipulation function, such as @strcat@.
|
---|
64 | Like C strings, characters in a @string@ are numbered from the left starting at 0 (because subscripting is zero-origin), and in \CFA numbered from the right starting at -1.
|
---|
65 | \begin{cquote}
|
---|
66 | \rm
|
---|
67 | \begin{tabular}{@{}rrrrll@{}}
|
---|
68 | \small\tt "a & \small\tt b & \small\tt c & \small\tt d & \small\tt e" \\
|
---|
69 | 0 & 1 & 2 & 3 & 4 & left to right index \\
|
---|
70 | -5 & -4 & -3 & -2 & -1 & right to left index
|
---|
71 | \end{tabular}
|
---|
72 | \end{cquote}
|
---|
73 | The following operations manipulate an instance of type @string@, where the discussion assumes the following declarations.
|
---|
74 | \begin{cfa}
|
---|
75 | #include @<string.hfa>@
|
---|
76 | @string@ s = "abcde", name = "MIKE", digit = "0123456789";
|
---|
77 | const char cs[$\,$] = "abc";
|
---|
78 | int i;
|
---|
79 | \end{cfa}
|
---|
80 | Note, the include file @<string.hfa>@ to access type @string@.
|
---|
81 |
|
---|
82 |
|
---|
83 | \subsection{Implicit String Conversions}
|
---|
84 |
|
---|
85 | The ability to convert from internal (machine) to external (human) format is useful in situations other than I/O.
|
---|
86 | Hence, the basic types @char@, @char *@, @int@, @double@, @_Complex@, including any signness and size variations, implicitly convert to type @string@ (as in Java).
|
---|
87 | \begin{cquote}
|
---|
88 | \setlength{\tabcolsep}{15pt}
|
---|
89 | \begin{tabular}{@{}l|ll|l@{}}
|
---|
90 | \begin{cfa}
|
---|
91 | string s;
|
---|
92 | s = 'x';
|
---|
93 | s = "abc";
|
---|
94 | s = cs;
|
---|
95 | s = 45hh;
|
---|
96 | s = 45h;
|
---|
97 | \end{cfa}
|
---|
98 | &
|
---|
99 | \begin{cfa}
|
---|
100 |
|
---|
101 | "x"
|
---|
102 | "abc"
|
---|
103 | "abc"
|
---|
104 | "45"
|
---|
105 | "45"
|
---|
106 | \end{cfa}
|
---|
107 | &
|
---|
108 | \begin{cfa}
|
---|
109 | s = (ssize_t)MIN;
|
---|
110 | s = (size_t)MAX;
|
---|
111 | s = 5.5;
|
---|
112 | s = 5.5L;
|
---|
113 | s = 5.5+3.4i;
|
---|
114 | s = 5.5L+3.4Li;
|
---|
115 | \end{cfa}
|
---|
116 | &
|
---|
117 | \begin{cfa}
|
---|
118 | "-9223372036854775808"
|
---|
119 | "18446744073709551615"
|
---|
120 | "5.5"
|
---|
121 | "5.5"
|
---|
122 | "5.5+3.4i"
|
---|
123 | "5.5+3.4i"
|
---|
124 | \end{cfa}
|
---|
125 | \end{tabular}
|
---|
126 | \end{cquote}
|
---|
127 | Conversions can be explicitly specified using a compound literal.
|
---|
128 | \begin{cfa}
|
---|
129 | s = (string){ "abc" }; $\C{// converts char * to string}$
|
---|
130 | s = (string){ 5 }; $\C{// converts int to string}$
|
---|
131 | s = (string){ 5.5 }; $\C{// converts double to string}$
|
---|
132 | \end{cfa}
|
---|
133 |
|
---|
134 | Conversions from @string@ to @char *@ attempt to be safe:
|
---|
135 | either by requiring the maximum length of the @char *@ storage (@strncpy@) or allocating the @char *@ storage for the string characters (ownership), meaning the programmer must free the storage.
|
---|
136 | Note, a C string is always null terminated, implying a minimum size of 1 character.
|
---|
137 | \begin{cquote}
|
---|
138 | \setlength{\tabcolsep}{15pt}
|
---|
139 | \begin{tabular}{@{}l|l@{}}
|
---|
140 | \begin{cfa}
|
---|
141 | strncpy( cs, s, sizeof(cs) );
|
---|
142 | char * cp = s;
|
---|
143 | delete( cp );
|
---|
144 | cp = s + ' ' + s;
|
---|
145 | delete( cp );
|
---|
146 | \end{cfa}
|
---|
147 | &
|
---|
148 | \begin{cfa}
|
---|
149 | "abc\0", in place
|
---|
150 | "abcde\0", malloc
|
---|
151 | ownership
|
---|
152 | "abcde abcde\0", malloc
|
---|
153 | ownership
|
---|
154 | \end{cfa}
|
---|
155 | \end{tabular}
|
---|
156 | \end{cquote}
|
---|
157 |
|
---|
158 |
|
---|
159 | \subsection{Length}
|
---|
160 |
|
---|
161 | The @len@ operation (short for @strlen@) returns the length of a C or \CFA string.
|
---|
162 | For compatibility, @strlen@ also works with \CFA strings.
|
---|
163 | \begin{cquote}
|
---|
164 | \setlength{\tabcolsep}{15pt}
|
---|
165 | \begin{tabular}{@{}l|l@{}}
|
---|
166 | \begin{cfa}
|
---|
167 | i = len( "" );
|
---|
168 | i = len( "abc" );
|
---|
169 | i = len( cs );
|
---|
170 | i = strlen( cs );
|
---|
171 | i = len( name );
|
---|
172 | i = strlen( name );
|
---|
173 | \end{cfa}
|
---|
174 | &
|
---|
175 | \begin{cfa}
|
---|
176 | 0
|
---|
177 | 3
|
---|
178 | 3
|
---|
179 | 3
|
---|
180 | 4
|
---|
181 | 4
|
---|
182 | \end{cfa}
|
---|
183 | \end{tabular}
|
---|
184 | \end{cquote}
|
---|
185 |
|
---|
186 |
|
---|
187 | \subsection{Comparison Operators}
|
---|
188 |
|
---|
189 | The binary relational, @<@, @<=@, @>@, @>=@, and equality, @==@, @!=@, operators compare \CFA string values using lexicographical ordering, where longer strings are greater than shorter strings.
|
---|
190 | In C, these operators compare the C string pointer not its value, which does not match programmer expectation.
|
---|
191 | C strings use function @strcmp@ to lexicographically compare the string value.
|
---|
192 | Java has the same issue with @==@ and @.equals@.
|
---|
193 |
|
---|
194 |
|
---|
195 | \subsection{Concatenation}
|
---|
196 |
|
---|
197 | The binary operators @+@ and @+=@ concatenate C @char@, @char *@ and \CFA strings, creating the sum of the characters.
|
---|
198 | \par\noindent
|
---|
199 | \begin{tabular}{@{}l|l@{\hspace{15pt}}l|l@{\hspace{15pt}}l|l@{}}
|
---|
200 | \begin{cfa}
|
---|
201 | s = "";
|
---|
202 | s = 'a' + 'b';
|
---|
203 | s = 'a' + "b";
|
---|
204 | s = "a" + 'b';
|
---|
205 | s = "a" + "b";
|
---|
206 | \end{cfa}
|
---|
207 | &
|
---|
208 | \begin{cfa}
|
---|
209 |
|
---|
210 | "ab"
|
---|
211 | "ab"
|
---|
212 | "ab"
|
---|
213 | "ab"
|
---|
214 | \end{cfa}
|
---|
215 | &
|
---|
216 | \begin{cfa}
|
---|
217 | s = "";
|
---|
218 | s = 'a' + 'b' + s;
|
---|
219 | s = 'a' + 'b' + s;
|
---|
220 | s = 'a' + "b" + s;
|
---|
221 | s = "a" + 'b' + s;
|
---|
222 | \end{cfa}
|
---|
223 | &
|
---|
224 | \begin{cfa}
|
---|
225 |
|
---|
226 | "ab"
|
---|
227 | "abab"
|
---|
228 | "ababab"
|
---|
229 | "abababab"
|
---|
230 | \end{cfa}
|
---|
231 | &
|
---|
232 | \begin{cfa}
|
---|
233 | s = "";
|
---|
234 | s = s + 'a' + 'b';
|
---|
235 | s = s + 'a' + "b";
|
---|
236 | s = s + "a" + 'b';
|
---|
237 | s = s + "a" + "b";
|
---|
238 | \end{cfa}
|
---|
239 | &
|
---|
240 | \begin{cfa}
|
---|
241 |
|
---|
242 | "ab"
|
---|
243 | "abab"
|
---|
244 | "ababab"
|
---|
245 | "abababab"
|
---|
246 | \end{cfa}
|
---|
247 | \end{tabular}
|
---|
248 | \par\noindent
|
---|
249 | However, including @<string.hfa>@ can result in ambiguous uses of the overloaded @+@ operator.\footnote{Combining multiple packages in any programming language can result in name clashes or ambiguities.}
|
---|
250 | While subtracting characters or pointers has a low-level use-case
|
---|
251 | \begin{cfa}
|
---|
252 | ch - '0' $\C[2in]{// find character offset}$
|
---|
253 | cs - cs2; $\C{// find pointer offset}\CRT$
|
---|
254 | \end{cfa}
|
---|
255 | addition is less obvious
|
---|
256 | \begin{cfa}
|
---|
257 | ch + 'b' $\C[2in]{// add character values}$
|
---|
258 | cs + 'a'; $\C{// move pointer cs['a']}\CRT$
|
---|
259 | \end{cfa}
|
---|
260 | There are legitimate use cases for arithmetic with @signed@/@unsigned@ characters (bytes), and these types are treated differently from @char@ in \CC and \CFA.
|
---|
261 | However, backwards compatibility makes it impossible to restrict or remove addition on type @char@.
|
---|
262 | Similarly, it is impossible to restrict or remove addition on type @char *@ because (unfortunately) it is subscripting: @cs + 'a'@ implies @cs['a']@ or @'a'[cs]@.
|
---|
263 |
|
---|
264 | The prior \CFA concatenation examples show complex mixed-mode interactions among @char@, @char *@, and @string@ (variables are the same as constants) work correctly.
|
---|
265 | The reason is that the \CFA type-system handles this kind of overloading well using the left-hand assignment-type and complex conversion costs.
|
---|
266 | Hence, the type system correctly handles all uses of addition (explicit or implicit) for @char *@.
|
---|
267 | \begin{cfa}
|
---|
268 | printf( "%s %s %s %c %c\n", "abc", cs, cs + 3, cs['a'], 'a'[cs] );
|
---|
269 | \end{cfa}
|
---|
270 | Only @char@ addition can result in ambiguities, and only when there is no left-hand information.
|
---|
271 | \begin{cfa}
|
---|
272 | ch = ch + 'b'; $\C[2in]{// LHS disambiguate, add character values}$
|
---|
273 | s = 'a' + 'b'; $\C{// LHS disambiguate, concatenate characters}$
|
---|
274 | printf( "%c\n", @'a' + 'b'@ ); $\C{// no LHS information, ambiguous}$
|
---|
275 | printf( "%c\n", @(return char)@('a' + 'b') ); $\C{// disambiguate with ascription cast}\CRT$
|
---|
276 | \end{cfa}
|
---|
277 | The ascription cast, @(return T)@, disambiguates by stating a (LHS) type to use during expression resolution (not a conversion).
|
---|
278 | Fortunately, character addition without LHS information is rare in C/\CFA programs, so repurposing the operator @+@ for @string@ types is not a problem.
|
---|
279 | Note, other programming languages that repurpose @+@ for concatenation, could have similar ambiguity issues.
|
---|
280 |
|
---|
281 | Interestingly, \CC cannot support this generality because it does not use the left-hand side of assignment in expression resolution.
|
---|
282 | While it can special case some combinations:
|
---|
283 | \begin{c++}
|
---|
284 | s = 'a' + s; $\C[2in]{// compiles in C++}$
|
---|
285 | s = "a" + s;
|
---|
286 | \end{c++}
|
---|
287 | it cannot generalize to any number of steps:
|
---|
288 | \begin{c++}
|
---|
289 | s = 'a' + 'b' + s; $\C{// does not compile in C++}\CRT$
|
---|
290 | s = "a" + "b" + s;
|
---|
291 | \end{c++}
|
---|
292 |
|
---|
293 |
|
---|
294 | \subsection{Repetition}
|
---|
295 |
|
---|
296 | The binary operators @*@ and @*=@ repeat a string $N$ times.
|
---|
297 | If $N = 0$, a zero length string, @""@, is returned.
|
---|
298 | \begin{cquote}
|
---|
299 | \setlength{\tabcolsep}{15pt}
|
---|
300 | \begin{tabular}{@{}l|l@{}}
|
---|
301 | \begin{cfa}
|
---|
302 | s = 'x' * 0;
|
---|
303 | s = 'x' * 3;
|
---|
304 | s = "abc" * 3;
|
---|
305 | s = (name + ' ') * 3;
|
---|
306 | \end{cfa}
|
---|
307 | &
|
---|
308 | \begin{cfa}
|
---|
309 | "
|
---|
310 | "xxx"
|
---|
311 | "abcabcabc"
|
---|
312 | "MIKE MIKE MIKE "
|
---|
313 | \end{cfa}
|
---|
314 | \end{tabular}
|
---|
315 | \end{cquote}
|
---|
316 | Like concatenation, there is a potential ambiguity with multiplication of characters;
|
---|
317 | multiplication for pointers does not exist in C.
|
---|
318 | \begin{cfa}
|
---|
319 | ch = ch * 3; $\C[2in]{// LHS disambiguate, multiply character values}$
|
---|
320 | s = 'a' * 3; $\C{// LHS disambiguate, concatenate characters}$
|
---|
321 | printf( "%c\n", @'a' * 3@ ); $\C{// no LHS information, ambiguous}$
|
---|
322 | printf( "%c\n", @(return char)@('a' * 3) ); $\C{// disambiguate with ascription cast}\CRT$
|
---|
323 | \end{cfa}
|
---|
324 | Fortunately, character multiplication without LHS information is even rarer than addition, so repurposing the operator @*@ for @string@ types is not a problem.
|
---|
325 |
|
---|
326 |
|
---|
327 | \subsection{Substring}
|
---|
328 | The substring operation returns a subset of a string starting at a position in the string and traversing a length or matching a pattern string.
|
---|
329 | \begin{cquote}
|
---|
330 | \setlength{\tabcolsep}{10pt}
|
---|
331 | \begin{tabular}{@{}l|ll|l@{}}
|
---|
332 | \multicolumn{2}{c}{\textbf{length}} & \multicolumn{2}{c}{\textbf{pattern}} \\
|
---|
333 | \begin{cfa}
|
---|
334 | s = name( 2, 2 );
|
---|
335 | s = name( 3, -2 );
|
---|
336 | s = name( 2, 8 );
|
---|
337 | s = name( 0, -1 );
|
---|
338 | s = name( -1, -1 );
|
---|
339 | s = name( -3 );
|
---|
340 | \end{cfa}
|
---|
341 | &
|
---|
342 | \begin{cfa}
|
---|
343 | "KE"
|
---|
344 | "IK"
|
---|
345 | "KE", clip length to 2
|
---|
346 | "", beyond string clip to null
|
---|
347 | "K"
|
---|
348 | "IKE", to end of string
|
---|
349 | \end{cfa}
|
---|
350 | &
|
---|
351 | \begin{cfa}
|
---|
352 | s = name( "IK" );
|
---|
353 | s = name( "WW" );
|
---|
354 |
|
---|
355 |
|
---|
356 |
|
---|
357 |
|
---|
358 | \end{cfa}
|
---|
359 | &
|
---|
360 | \begin{cfa}
|
---|
361 | "IK"
|
---|
362 | ""
|
---|
363 |
|
---|
364 |
|
---|
365 |
|
---|
366 |
|
---|
367 | \end{cfa}
|
---|
368 | \end{tabular}
|
---|
369 | \end{cquote}
|
---|
370 | A negative starting position is a specification from the right end of the string.
|
---|
371 | A negative length means that characters are selected in the opposite (right to left) direction from the starting position.
|
---|
372 | If the substring request extends beyond the beginning or end of the string, it is clipped (shortened) to the bounds of the string.
|
---|
373 | If the substring request is completely outside of the original string, a null string is returned.
|
---|
374 | The pattern-form either returns the pattern string is the pattern matches or a null string if the pattern does not match.
|
---|
375 | The usefulness of this mechanism is discussed next.
|
---|
376 |
|
---|
377 | The substring operation can appear on the left side of assignment, where it defines a replacement substring.
|
---|
378 | The length of the right string may be shorter, the same, or longer than the length of left string.
|
---|
379 | Hence, the left string may decrease, stay the same, or increase in length.
|
---|
380 | \begin{cquote}
|
---|
381 | \setlength{\tabcolsep}{15pt}
|
---|
382 | \begin{tabular}{@{}l|l@{}}
|
---|
383 | \begin{cfa}[escapechar={}]
|
---|
384 | digit( 3, 3 ) = "";
|
---|
385 | digit( 4, 3 ) = "xyz";
|
---|
386 | digit( 7, 0 ) = "***";
|
---|
387 | digit(-4, 3 ) = "$$$";
|
---|
388 | digit( 5 ) = "LLL";
|
---|
389 | \end{cfa}
|
---|
390 | &
|
---|
391 | \begin{cfa}[escapechar={}]
|
---|
392 | "0126789"
|
---|
393 | "0126xyz"
|
---|
394 | "0126xyz"
|
---|
395 | "012$$$z"
|
---|
396 | "012$$LLL"
|
---|
397 | \end{cfa}
|
---|
398 | \end{tabular}
|
---|
399 | \end{cquote}
|
---|
400 | Now pattern matching is useful on the left-hand side of assignment.
|
---|
401 | \begin{cquote}
|
---|
402 | \setlength{\tabcolsep}{15pt}
|
---|
403 | \begin{tabular}{@{}l|l@{}}
|
---|
404 | \begin{cfa}[escapechar={}]
|
---|
405 | digit( "$$" ) = "345";
|
---|
406 | digit( "LLL") = "6789";
|
---|
407 | \end{cfa}
|
---|
408 | &
|
---|
409 | \begin{cfa}
|
---|
410 | "012345LLL"
|
---|
411 | "0123456789"
|
---|
412 | \end{cfa}
|
---|
413 | \end{tabular}
|
---|
414 | \end{cquote}
|
---|
415 | Extending the pattern to a regular expression is a possible extension.
|
---|
416 |
|
---|
417 | The replace operation extensions substring to substitute all occurrences.
|
---|
418 | \begin{cquote}
|
---|
419 | \setlength{\tabcolsep}{15pt}
|
---|
420 | \begin{tabular}{@{}l|l@{}}
|
---|
421 | \begin{cfa}
|
---|
422 | s = replace( "PETER", "E", "XX" );
|
---|
423 | s = replace( "PETER", "ET", "XX" );
|
---|
424 | s = replace( "PETER", "W", "XX" );
|
---|
425 | \end{cfa}
|
---|
426 | &
|
---|
427 | \begin{cfa}
|
---|
428 | "PXXTXXR"
|
---|
429 | "PXXER"
|
---|
430 | "PETER"
|
---|
431 | \end{cfa}
|
---|
432 | \end{tabular}
|
---|
433 | \end{cquote}
|
---|
434 | The replacement is done left-to-right and substituted text is not examined for replacement.
|
---|
435 |
|
---|
436 |
|
---|
437 | \subsection{Searching}
|
---|
438 |
|
---|
439 | The find operation returns the position of the first occurrence of a key in a string.
|
---|
440 | If the key does not appear in the string, the length of the string is returned.
|
---|
441 | \begin{cquote}
|
---|
442 | \setlength{\tabcolsep}{15pt}
|
---|
443 | \begin{tabular}{@{}l|l@{}}
|
---|
444 | \begin{cfa}
|
---|
445 | i = find( digit, '3' );
|
---|
446 | i = find( digit, "45" );
|
---|
447 | i = find( digit, "abc" );
|
---|
448 | \end{cfa}
|
---|
449 | &
|
---|
450 | \begin{cfa}
|
---|
451 | 3
|
---|
452 | 4
|
---|
453 | 10
|
---|
454 | \end{cfa}
|
---|
455 | \end{tabular}
|
---|
456 | \end{cquote}
|
---|
457 |
|
---|
458 | A character-class operation indicates if a string is composed completely of a particular class of characters, \eg, alphabetic, numeric, vowels, \etc.
|
---|
459 | \begin{cquote}
|
---|
460 | \setlength{\tabcolsep}{15pt}
|
---|
461 | \begin{tabular}{@{}l|l@{}}
|
---|
462 | \begin{cfa}
|
---|
463 | charclass vowels{ "aeiouy" };
|
---|
464 | i = include( "aaeiuyoo", vowels );
|
---|
465 | i = include( "aabiuyoo", vowels );
|
---|
466 | \end{cfa}
|
---|
467 | &
|
---|
468 | \begin{cfa}
|
---|
469 |
|
---|
470 | 8 // compliant
|
---|
471 | 2 // b non-compliant
|
---|
472 | \end{cfa}
|
---|
473 | \end{tabular}
|
---|
474 | \end{cquote}
|
---|
475 | @vowels@ defines a character class and function @include@ checks if all characters in the string appear in the class (compliance).
|
---|
476 | The position of the last character is returned if the string is compliant or the position of the first non-compliant character.
|
---|
477 | There is no relationship between the order of characters in the two strings.
|
---|
478 | Function @exclude@ is the reverse of @include@, checking if all characters in the string are excluded from the class (compliance).
|
---|
479 | \begin{cquote}
|
---|
480 | \setlength{\tabcolsep}{15pt}
|
---|
481 | \begin{tabular}{@{}l|l@{}}
|
---|
482 | \begin{cfa}
|
---|
483 | i = exclude( "cdbfghmk", vowels );
|
---|
484 | i = exclude( "cdyfghmk", vowels );
|
---|
485 | \end{cfa}
|
---|
486 | &
|
---|
487 | \begin{cfa}
|
---|
488 | 8 // compliant
|
---|
489 | 2 // y non-compliant
|
---|
490 | \end{cfa}
|
---|
491 | \end{tabular}
|
---|
492 | \end{cquote}
|
---|
493 | Both forms can return the longest substring of compliant characters.
|
---|
494 | \begin{cquote}
|
---|
495 | \setlength{\tabcolsep}{15pt}
|
---|
496 | \begin{tabular}{@{}l|l@{}}
|
---|
497 | \begin{cfa}
|
---|
498 | s = include( "aaeiuyoo", vowels );
|
---|
499 | s = include( "aabiuyoo", vowels );
|
---|
500 | s = exclude( "cdbfghmk", vowels );
|
---|
501 | s = exclude( "cdyfghmk", vowels );
|
---|
502 | \end{cfa}
|
---|
503 | &
|
---|
504 | \begin{cfa}
|
---|
505 | "aaeiuyoo"
|
---|
506 | "aa"
|
---|
507 | "cdbfghmk"
|
---|
508 | "cd"
|
---|
509 | \end{cfa}
|
---|
510 | \end{tabular}
|
---|
511 | \end{cquote}
|
---|
512 |
|
---|
513 | There are also versions of @include@ and @exclude@, returning a position or string, taking a validation function, like one of the C character-class routines.\footnote{It is part of the hereditary of C that these function take and return an \lstinline{int} rather than a \lstinline{bool}, which affects the function type.}
|
---|
514 | \begin{cquote}
|
---|
515 | \setlength{\tabcolsep}{15pt}
|
---|
516 | \begin{tabular}{@{}l|l@{}}
|
---|
517 | \begin{cfa}
|
---|
518 | i = include( "1FeC34aB", @isxdigit@ );
|
---|
519 | i = include( ".,;'!\"", @ispunct@ );
|
---|
520 | i = include( "XXXx", @isupper@ );
|
---|
521 | \end{cfa}
|
---|
522 | &
|
---|
523 | \begin{cfa}
|
---|
524 | 8 // compliant
|
---|
525 | 6 // compliant
|
---|
526 | 3 // non-compliant
|
---|
527 | \end{cfa}
|
---|
528 | \end{tabular}
|
---|
529 | \end{cquote}
|
---|
530 | These operations perform an \emph{apply} of the validation function to each character, where the function returns a boolean indicating a stopping condition for the search.
|
---|
531 | The position of the last character is returned if the string is compliant or the position of the first non-compliant character.
|
---|
532 |
|
---|
533 | The translate operation returns a string with each character transformed by one of the C character transformation functions.
|
---|
534 | \begin{cquote}
|
---|
535 | \setlength{\tabcolsep}{15pt}
|
---|
536 | \begin{tabular}{@{}l|l@{}}
|
---|
537 | \begin{cfa}
|
---|
538 | s = translate( "abc", @toupper@ );
|
---|
539 | s = translate( "ABC", @tolower@ );
|
---|
540 | int tospace( int c ) { return isspace( c ) ? ' ' : c; }
|
---|
541 | s = translate( "X X\tX\nX", @tospace@ );
|
---|
542 | \end{cfa}
|
---|
543 | &
|
---|
544 | \begin{cfa}
|
---|
545 | "ABC"
|
---|
546 | "abc"
|
---|
547 |
|
---|
548 | "X X X X"
|
---|
549 | \end{cfa}
|
---|
550 | \end{tabular}
|
---|
551 | \end{cquote}
|
---|
552 |
|
---|
553 |
|
---|
554 | \subsection{Returning N on Search Failure}
|
---|
555 |
|
---|
556 | Some of the prior string operations are composite, \eg string operations returning the longest substring of compliant characters (@include@) are built using a search and then substring the appropriate text.
|
---|
557 | However, string search can fail, which is reported as an alternate search outcome, possibly an exception.
|
---|
558 | Many string libraries use a return code to indicate search failure, with a failure value of @0@ or @-1@ (PL/I~\cite{PLI} returns @0@).
|
---|
559 | This semantics leads to the awkward pattern, which can appear many times in a string library or user code.
|
---|
560 | \begin{cfa}
|
---|
561 | i = exclude( s, alpha );
|
---|
562 | if ( i != -1 ) return s( 0, i );
|
---|
563 | else return "";
|
---|
564 | \end{cfa}
|
---|
565 |
|
---|
566 | \CFA adopts a return code but the failure value is taken from the index-of function in APL~\cite{apl}, which returns the length of the target string $N$ (or $N+1$ for 1 origin).
|
---|
567 | This semantics allows many search and substring functions to be written without conditions, \eg:
|
---|
568 | \begin{cfa}
|
---|
569 | string include( const string & s, int (*f)( int ) ) { return @s( 0, include( s, f ) )@; }
|
---|
570 | string exclude( const string & s, int (*f)( int ) ) { return @s( 0, exclude( s, f ) )@; }
|
---|
571 | \end{cfa}
|
---|
572 | In string systems with an $O(1)$ length operator, checking for failure is low cost.
|
---|
573 | \begin{cfa}
|
---|
574 | if ( include( line, alpha ) == len( line ) ) ... // not found, 0 origin
|
---|
575 | \end{cfa}
|
---|
576 | \VRef[Figure]{f:ExtractingWordsText} compares \CC and \CFA string code for extracting words from a line of text, repeatedly removing non-word text and then a word until the line is empty.
|
---|
577 | The \CFA code is simpler solely because of the choice for indicating search failure.
|
---|
578 | (A simplification of the \CC version is to concatenate a sentinel character at the end of the line so the call to @find_first_not_of@ does not fail.)
|
---|
579 |
|
---|
580 | \begin{figure}
|
---|
581 | \begin{cquote}
|
---|
582 | \setlength{\tabcolsep}{15pt}
|
---|
583 | \begin{tabular}{@{}l|l@{}}
|
---|
584 | \multicolumn{1}{c}{\textbf{\CC}} & \multicolumn{1}{c}{\textbf{\CFA}} \\
|
---|
585 | \begin{cfa}
|
---|
586 | for ( ;; ) {
|
---|
587 | string::size_type posn = line.find_first_of( alpha );
|
---|
588 | if ( posn == string::npos ) break;
|
---|
589 | line = line.substr( posn );
|
---|
590 | posn = line.find_first_not_of( alpha );
|
---|
591 | if ( posn != string::npos ) {
|
---|
592 | cout << line.substr( 0, posn ) << endl;
|
---|
593 | line = line.substr( posn );
|
---|
594 | } else {
|
---|
595 | cout << line << endl;
|
---|
596 | line = "";
|
---|
597 | }
|
---|
598 | }
|
---|
599 | \end{cfa}
|
---|
600 | &
|
---|
601 | \begin{cfa}
|
---|
602 | for () {
|
---|
603 | size_t posn = exclude( line, alpha );
|
---|
604 | if ( posn == len( line ) ) break;
|
---|
605 | line = line( posn );
|
---|
606 | posn = include( line, alpha );
|
---|
607 |
|
---|
608 | sout | line( 0, posn );
|
---|
609 | line = line( posn );
|
---|
610 |
|
---|
611 |
|
---|
612 |
|
---|
613 |
|
---|
614 | }
|
---|
615 | \end{cfa}
|
---|
616 | \end{tabular}
|
---|
617 | \end{cquote}
|
---|
618 | \caption{Extracting Words from Line of Text}
|
---|
619 | \label{f:ExtractingWordsText}
|
---|
620 | \end{figure}
|
---|
621 |
|
---|
622 |
|
---|
623 | \subsection{C Compatibility}
|
---|
624 |
|
---|
625 | To ease conversion from C to \CFA, \CFA provides companion C @string@ functions.
|
---|
626 | Hence, it is possible to convert a block of C string operations to \CFA strings just by changing the type @char *@ to @string@.
|
---|
627 | \begin{cquote}
|
---|
628 | \setlength{\tabcolsep}{15pt}
|
---|
629 | \begin{tabular}{@{}ll@{}}
|
---|
630 | \begin{cfa}
|
---|
631 | char s[32]; // string s;
|
---|
632 | strlen( s );
|
---|
633 | strnlen( s, 3 );
|
---|
634 | strcmp( s, "abc" );
|
---|
635 | strncmp( s, "abc", 3 );
|
---|
636 | \end{cfa}
|
---|
637 | &
|
---|
638 | \begin{cfa}
|
---|
639 |
|
---|
640 | strcpy( s, "abc" );
|
---|
641 | strncpy( s, "abcdef", 3 );
|
---|
642 | strcat( s, "xyz" );
|
---|
643 | strncat( s, "uvwxyz", 3 );
|
---|
644 | \end{cfa}
|
---|
645 | \end{tabular}
|
---|
646 | \end{cquote}
|
---|
647 | However, the conversion fails with I/O because @printf@ cannot print a @string@ using format code @%s@ because \CFA strings are not null terminated.
|
---|
648 | Nevertheless, this capability does provide a useful starting point for conversion to safer \CFA strings.
|
---|
649 |
|
---|
650 |
|
---|
651 | \subsection{I/O Operators}
|
---|
652 |
|
---|
653 | The ability to input and output strings is as essential as for any other type.
|
---|
654 | The goal for character I/O is to also work with groups rather than individual characters.
|
---|
655 | A comparison with \CC string I/O is presented as a counterpoint to \CFA string I/O.
|
---|
656 |
|
---|
657 | The \CC output @<<@ and input @>>@ operators are defined on type @string@.
|
---|
658 | \CC output for @char@, @char *@, and @string@ are similar.
|
---|
659 | The \CC manipulators are @setw@, and its associated width controls @left@, @right@ and @setfill@.
|
---|
660 | \begin{cquote}
|
---|
661 | \setlength{\tabcolsep}{15pt}
|
---|
662 | \begin{tabular}{@{}l|l@{}}
|
---|
663 | \begin{c++}
|
---|
664 | string s = "abc";
|
---|
665 | cout << setw(10) << left << setfill( 'x' ) << s << endl;
|
---|
666 | \end{c++}
|
---|
667 | &
|
---|
668 | \begin{c++}
|
---|
669 |
|
---|
670 | "abcxxxxxxx"
|
---|
671 | \end{c++}
|
---|
672 | \end{tabular}
|
---|
673 | \end{cquote}
|
---|
674 |
|
---|
675 | The \CFA input/output operator @|@ is defined on type @string@.
|
---|
676 | \CFA output for @char@, @char *@, and @string@ are similar.
|
---|
677 | The \CFA manipulators are @bin@, @oct@, @hex@, @wd@, and its associated width control and @left@.
|
---|
678 | \begin{cquote}
|
---|
679 | \setlength{\tabcolsep}{15pt}
|
---|
680 | \begin{tabular}{@{}l|l@{}}
|
---|
681 | \begin{cfa}
|
---|
682 | string s = "abc";
|
---|
683 | sout | bin( s ) | nl
|
---|
684 | | oct( s ) | nl
|
---|
685 | | hex( s ) | nl
|
---|
686 | | wd( 10, s ) | nl
|
---|
687 | | wd( 10, 2, s ) | nl
|
---|
688 | | left( wd( 10, s ) );
|
---|
689 | \end{cfa}
|
---|
690 | &
|
---|
691 | \begin{cfa}
|
---|
692 |
|
---|
693 | "0b1100001 0b1100010 0b1100011"
|
---|
694 | "0141 0142 0143"
|
---|
695 | "0x61 0x62 0x63"
|
---|
696 | " abc"
|
---|
697 | " ab"
|
---|
698 | "abc "
|
---|
699 | \end{cfa}
|
---|
700 | \end{tabular}
|
---|
701 | \end{cquote}
|
---|
702 | \CC @setfill@ is not considered an important string manipulator.
|
---|
703 |
|
---|
704 | \CC input matching for @char@, @char *@, and @string@ are similar, where \emph{all} input characters are read from the current point in the input stream to the end of the type size, format width, whitespace, end of line (@'\n'@), or end of file.
|
---|
705 | The \CC manipulator is @setw@ to restrict the size.
|
---|
706 | Reading into a @char@ is safe as the size is 1, @char *@ is unsafe without using @setw@ to constraint the length (which includes @'\0'@), @string@ is safe as its grows dynamically as characters are read.
|
---|
707 | \begin{cquote}
|
---|
708 | \setlength{\tabcolsep}{15pt}
|
---|
709 | \begin{tabular}{@{}l|l@{}}
|
---|
710 | \begin{c++}
|
---|
711 | char ch, c[10];
|
---|
712 | string s;
|
---|
713 | cin >> ch >> setw( 5 ) >> c >> s;
|
---|
714 | @abcde fg@
|
---|
715 | \end{c++}
|
---|
716 | &
|
---|
717 | \begin{c++}
|
---|
718 |
|
---|
719 |
|
---|
720 | 'a' "bcde" "fg"
|
---|
721 |
|
---|
722 | \end{c++}
|
---|
723 | \end{tabular}
|
---|
724 | \end{cquote}
|
---|
725 | Input text can be \emph{gulped}, including whitespace, from the current point to an arbitrary delimiter character using @getline@.
|
---|
726 |
|
---|
727 | The \CFA philosophy for input is that, for every constant type in C, these constants should be usable as input.
|
---|
728 | For example, the complex constant @3.5+4.1i@ can appear as input to a complex variable.
|
---|
729 | \CFA input matching for @char@, @char *@, and @string@ are similar.
|
---|
730 | C-strings may only be read with a width field, which should match the string size.
|
---|
731 | Certain input manipulators support a scanset, which is a simple regular expression from @printf@.
|
---|
732 | The \CFA manipulators for these types are @wdi@,\footnote{Due to an overloading issue in the type-resolver, the input width name must be temporarily different from the output, \lstinline{wdi} versus \lstinline{wd}.} and its associated width control and @left@, @quote@, @incl@, @excl@, and @getline@.
|
---|
733 | \begin{cquote}
|
---|
734 | \setlength{\tabcolsep}{10pt}
|
---|
735 | \begin{tabular}{@{}l|l@{}}
|
---|
736 | \begin{c++}
|
---|
737 | char ch, c[10];
|
---|
738 | string s;
|
---|
739 | sin | ch | wdi( 5, c ) | s;
|
---|
740 | @abcde fg@
|
---|
741 | sin | quote( ch ) | quote( wdi( sizeof(c), c ) ) | quote( s, '[', ']' ) | nl;
|
---|
742 | @'a' "bcde" [fg]@
|
---|
743 | sin | incl( "a-zA-Z0-9 ?!&\n", s ) | nl;
|
---|
744 | @x?&000xyz TOM !.@
|
---|
745 | sin | excl( "a-zA-Z0-9 ?!&\n", s );
|
---|
746 | @<>{}{}STOP@
|
---|
747 | \end{c++}
|
---|
748 | &
|
---|
749 | \begin{c++}
|
---|
750 |
|
---|
751 |
|
---|
752 | 'a' "bcde" "fg"
|
---|
753 |
|
---|
754 | 'a' "bcde" "fg"
|
---|
755 |
|
---|
756 | "x?&000xyz TOM !"
|
---|
757 |
|
---|
758 | "<>{}{}"
|
---|
759 |
|
---|
760 | \end{c++}
|
---|
761 | \end{tabular}
|
---|
762 | \end{cquote}
|
---|
763 | Note, the ability to read in quoted strings with whitespace to match with program string constants.
|
---|
764 | The @nl@ at the end of an input ignores the rest of the line.
|
---|
765 |
|
---|
766 |
|
---|
767 | \subsection{Assignment}
|
---|
768 |
|
---|
769 | While \VRef[Figure]{f:StrApiCompare} emphasizes cross-language similarities, it elides many specific operational differences.
|
---|
770 | For example, the \CC @replace@ function selects a substring in the target and substitutes it with the source string, which can be smaller or larger than the substring.
|
---|
771 | \CC modifies the mutable receiver object, replacing by position (zero origin) and length.
|
---|
772 | \begin{cquote}
|
---|
773 | \setlength{\tabcolsep}{15pt}
|
---|
774 | \begin{tabular}{@{}l|l@{}}
|
---|
775 | \begin{c++}
|
---|
776 | string s1 = "abcde";
|
---|
777 | s1.replace( 2, 3, "xy" );
|
---|
778 | \end{c++}
|
---|
779 | &
|
---|
780 | \begin{c++}
|
---|
781 |
|
---|
782 | "abxy"
|
---|
783 | \end{c++}
|
---|
784 | \end{tabular}
|
---|
785 | \end{cquote}
|
---|
786 | Java cannot modify the receiver (immutable strings) so it returns a new string, replacing by text.
|
---|
787 | \label{p:JavaReplace}
|
---|
788 | \begin{cquote}
|
---|
789 | \setlength{\tabcolsep}{15pt}
|
---|
790 | \begin{tabular}{@{}l|l@{}}
|
---|
791 | \begin{java}
|
---|
792 | String s = "abcde";
|
---|
793 | String r = s.replace( "cde", "xy" );
|
---|
794 | \end{java}
|
---|
795 | &
|
---|
796 | \begin{java}
|
---|
797 |
|
---|
798 | "abxy"
|
---|
799 | \end{java}
|
---|
800 | \end{tabular}
|
---|
801 | \end{cquote}
|
---|
802 | Java also provides a mutable @StringBuffer@, replacing by position (zero origin) and length.
|
---|
803 | \begin{cquote}
|
---|
804 | \setlength{\tabcolsep}{15pt}
|
---|
805 | \begin{tabular}{@{}l|l@{}}
|
---|
806 | \begin{java}
|
---|
807 | StringBuffer sb = new StringBuffer( "abcde" );
|
---|
808 | sb.replace( 2, 5, "xy" );
|
---|
809 | \end{java}
|
---|
810 | &
|
---|
811 | \begin{java}
|
---|
812 |
|
---|
813 | "abxy"
|
---|
814 | \end{java}
|
---|
815 | \end{tabular}
|
---|
816 | \end{cquote}
|
---|
817 | However, there are anomalies.
|
---|
818 | @StringBuffer@'s @substring@ returns a @String@ copy that is immutable rather than modifying the receiver.
|
---|
819 | As well, the operations are asymmetric, \eg @String@ has @replace@ by text but not replace by position and vice versa for @StringBuffer@.
|
---|
820 |
|
---|
821 | More significant operational differences relate to storage management, often appearing through assignment (@target = source@), and are summarized in \VRef[Figure]{f:StrSemanticCompare}, which defines properties type abstraction, state, symmetry, and referent.
|
---|
822 | The following discussion justifies the figure's yes/no entries per language.
|
---|
823 |
|
---|
824 | \begin{figure}
|
---|
825 | \setlength{\extrarowheight}{2pt}
|
---|
826 | \begin{tabularx}{\textwidth}{@{}p{0.6in}XXcccc@{}}
|
---|
827 | & & & \multicolumn{4}{@{}c@{}}{\underline{Supports Helpful?}} \\
|
---|
828 | & Required & Helpful & C & \CC & Java & \CFA \\
|
---|
829 | \hline
|
---|
830 | Type abst'n
|
---|
831 | & Low-level: The string type is a varying amount of text communicated via a parameter or return.
|
---|
832 | & High-level: The string-typed relieves the user of managing memory for the text.
|
---|
833 | & no & yes & yes & yes \\
|
---|
834 | \hline
|
---|
835 | State
|
---|
836 | & \multirow{2}{2in}
|
---|
837 | {Fast Initialize: The target receives the characters of the source without copying the characters, resulting in an Alias or Snapshot.}
|
---|
838 | & Alias: The target variable names the source text; changes made in either variable are visible in both.
|
---|
839 | & yes & yes & no & yes \\
|
---|
840 | \cline{3-7}
|
---|
841 | &
|
---|
842 | & Snapshot: Subsequent operations on either the source or target variable do not affect the other.
|
---|
843 | & no & no & yes & yes \\
|
---|
844 | \hline
|
---|
845 | Symmetry
|
---|
846 | & Laxed: The target's type is anything string-like; it may have a different status concerning ownership.
|
---|
847 | & Strict: The target's type is the same as the source; both strings are equivalent peers concerning ownership.
|
---|
848 | & N/A & no & yes & yes \\
|
---|
849 | \hline
|
---|
850 | Referent
|
---|
851 | & Variable-Constrained: The target can accept the entire text of the source.
|
---|
852 | & Fragment: The target can accept an arbitrary substring of the source.
|
---|
853 | & no & no & yes & yes
|
---|
854 | \end{tabularx}
|
---|
855 |
|
---|
856 | \noindent
|
---|
857 | Notes
|
---|
858 | \begin{itemize}[parsep=0pt]
|
---|
859 | \item
|
---|
860 | All languages support Required in all criteria.
|
---|
861 | \item
|
---|
862 | A language gets ``Supports Helpful'' in one criterion if it can do so without sacrificing the Required achievement on all other criteria.
|
---|
863 | \item
|
---|
864 | The C ``string'' is @char *@, under the conventions of @<string.h>@. Because this type does not manage a text allocation, symmetry does not apply.
|
---|
865 | \item
|
---|
866 | The Java @String@ class is analyzed; its @StringBuffer@ class behaves similarly to \CC.
|
---|
867 | \end{itemize}
|
---|
868 | \caption{Comparison of languages' strings, storage management perspective.}
|
---|
869 | \label{f:StrSemanticCompare}
|
---|
870 | \end{figure}
|
---|
871 |
|
---|
872 | In C, these declarations are very different.
|
---|
873 | \begin{cfa}
|
---|
874 | char x[$\,$] = "abcde";
|
---|
875 | char * y = "abcde";
|
---|
876 | \end{cfa}
|
---|
877 | Both associate the declared name with the fixed, six contiguous bytes: @{'a', 'b', 'c', 'd', 'e', 0}@.
|
---|
878 | But @x@ is allocated on the stack (with values filled at the declaration), while @y@ refers to the executable's read-only data-section.
|
---|
879 | With @x@ representing an allocation, it offers information in @sizeof(x)@ that @y@ does not.
|
---|
880 | But this extra information is second-class, as it can only be used in the immediate lexical context, \ie it cannot be passed to string operations or user functions.
|
---|
881 | Only pointers to text buffers are first-class, and discussed further.
|
---|
882 | \begin{cfa}
|
---|
883 | char * s = "abcde";
|
---|
884 | char * s1 = s; $\C[2.25in]{// alias state, N/A symmetry, variable-constrained referent}$
|
---|
885 | char * s2 = &s[1]; $\C{// alias state, N/A symmetry, variable-constrained referent}$
|
---|
886 | char * s3 = &s2[1]; $\C{// alias state, N/A symmetry, variable-constrained referent}\CRT$
|
---|
887 | printf( "%s %s %s %s\n", s, s1, s2, s3 );
|
---|
888 | $\texttt{\small abcde abcde bcde cde}$
|
---|
889 | \end{cfa}
|
---|
890 | Note, all of these aliased strings rely on the single null termination character at the end of @s@.
|
---|
891 | The issue of symmetry does not apply to a low-level API because no management of a text buffer is provided.
|
---|
892 | With the @char *@ type not managing the text storage, there is no ownership question, \ie operations on @s1@ or @s2@ never lead to their memory becoming reusable.
|
---|
893 | While @s3@ is a valid C-string that contains a proper substring of @s1@, the @s3@ technique does not constitute having a fragment referent because null termination implies the substring cannot be chosen arbitrarily; the technique works only for suffixes.
|
---|
894 |
|
---|
895 | In \CC, @string@ offers a high-level abstraction.
|
---|
896 | \begin{cfa}
|
---|
897 | string s = "abcde";
|
---|
898 | string & s1 = s; $\C[2.25in]{// alias state, lax symmetry, variable-constrained referent}$
|
---|
899 | string s2 = s; $\C{// no fast-initialize (strict symmetry, variable-constrained referent)}$
|
---|
900 | string s3 = s.substr( 1, 2 ); $\C{// no fast-initialize (strict symmetry, fragment referent)}$
|
---|
901 | string s4 = s3.substr( 1, 1 ); $\C{// no fast-initialize (strict symmetry, fragment referent)}$
|
---|
902 | cout << s << ' ' << s1 << ' ' << s2 << ' ' << s3 << ' ' << s4 << endl;
|
---|
903 | $\texttt{\small abcde abcde abcde bc c}$
|
---|
904 | string & s5 = s.substr(2,4); $\C{// error: cannot point to temporary}\CRT$
|
---|
905 | \end{cfa}
|
---|
906 | The @s1@ lax symmetry reflects how its validity depends on the lifetime of @s@.
|
---|
907 | It is common practice in \CC to use the @s1@-style for a by-reference function parameter.
|
---|
908 | Doing so assumes that the callee only uses the referenced string for the duration of the call, \ie no storing the parameter (as a reference) for later.
|
---|
909 | So, when the called function is a constructor, its definition typically uses an @s2@-style copy-initialization.
|
---|
910 | Exceptions to this pattern are possible, but require the programmer to assure safety where the type system does not.
|
---|
911 | The @s3@ initialization must copy the substring to support a subsequent @c_str@ call, which provides null-termination, generally at a different position than the source string's.
|
---|
912 | @s2@ assignment could be made fast, by reference-counting the text area and using copy-on-write, but would require an implementation upgrade.
|
---|
913 |
|
---|
914 | In Java, @String@ also offers a high-level abstraction:
|
---|
915 | \begin{java}
|
---|
916 | String s = "abcde";
|
---|
917 | String s1 = s; $\C[2.25in]{// snapshot state, strict symmetry, variable-constrained referent}$
|
---|
918 | String s2 = s.substring( 1, 3 ); $\C{// snapshot state (possible), strict symmetry, fragment referent}$
|
---|
919 | String s3 = s2.substring( 1, 2 ); $\C{// snapshot state (possible), strict symmetry, fragment referent}\CRT$
|
---|
920 | System.out.println( s + ' ' + s1 + ' ' + s2 + ' ' + s3 );
|
---|
921 | System.out.println( (s == s1) + " " + (s == s2) + " " + (s2 == s3) );
|
---|
922 | $\texttt{\small abcde abcde bc c}$
|
---|
923 | $\texttt{\small true false false}$
|
---|
924 | \end{java}
|
---|
925 | Note, Java's @substring@ takes a start and end position, rather than a start position and length.
|
---|
926 | Here, facts about Java's implicit pointers and pointer equality can over complicate the picture, and so are ignored.
|
---|
927 | Furthermore, Java's string immutability means string variables behave as simple values.
|
---|
928 | The result in @s1@ is the pointer in @s@, and their pointer equality confirm no time is spent copying characters.
|
---|
929 | With @s2@, the case for fast-copy is more subtle.
|
---|
930 | Certainly, its value is not pointer-equal to @s@, implying at least a further allocation.
|
---|
931 | But because Java is \emph{not} constrained to use a null-terminated representation, a standard-library implementation is free to refer to the source characters in-place.
|
---|
932 | Java does not meet the aliasing requirement because immutability makes it impossible to modify.
|
---|
933 | Java's @StringBuffer@ provides aliasing (see @replace@ example on \VPageref{p:JavaReplace}), though without supporting symmetric treatment of a fragment referent, \eg @substring@ of a @StringBuffer@ is a @String@;
|
---|
934 | as a result, @StringBuffer@ scores as \CC.
|
---|
935 | The easy symmetry that the Java string enjoys is aided by Java's garbage collection; Java's @s1@ is doing effectively the operation of \CC's @s1@, though without the consequence of complicating memory management.
|
---|
936 |
|
---|
937 | % former \PAB{What complex storage management is going on here?}
|
---|
938 | % answer: the variable names in the sentence were out of date; fixed
|
---|
939 |
|
---|
940 | Finally, in \CFA, @string@ also offers a high-level abstraction:
|
---|
941 | \begin{cfa}
|
---|
942 | string s = "abcde";
|
---|
943 | string & s1 = s; $\C[2.25in]{// alias state, lax symmetry, variable-constrained referent}$
|
---|
944 | string s2 = s; $\C{// snapshot state, strict symmetry, variable-constrained referent}$
|
---|
945 | string s3 = s`share; $\C{// alias state, strict symmetry, variable-constrained referent}$
|
---|
946 | string s4 = s( 1, 2 ); $\C{// snapshot state, strict symmetry, fragment referent}$
|
---|
947 | string s5 = s4( 1, 1 )`share'; $\C{// alias state, strict symmetry, fragment referent}\CRT$
|
---|
948 | sout | s | s1 | s2 | s3 | s4 | s5;
|
---|
949 | $\texttt{\small abcde abcde abcde abcde bc c}$
|
---|
950 | \end{cfa}
|
---|
951 | % all helpful criteria of \VRef[Figure]{f:StrSemanticCompare} are satisfied.
|
---|
952 | The \CFA string manages storage, handles all assignments, including those of fragment referents with fast initialization, provides the choice between snapshot and alias semantics, and does so symmetrically with one type (which assures text validity according to the lifecycles of the string variables).
|
---|
953 | The @s1@ case is the same in \CFA as in \CC.
|
---|
954 | But the \CFA @s2@ delivers a fast snapshot, while the \CC @s2@ does not.
|
---|
955 | \CFA offers the snapshot-vs-alias choice in @s2@-vs-@s3@ and @s4@-vs-@s5@.
|
---|
956 | Regardless of snapshot-vs-alias and fragment-vs-whole, the target is always of the same @string@ type.
|
---|
957 |
|
---|
958 | % former \PAB{Need to discuss the example, as for the other languages.}
|
---|
959 | % answer: done
|
---|
960 |
|
---|
961 |
|
---|
962 | \subsection{Logical Overlap}
|
---|
963 |
|
---|
964 | It may be unfamiliar to combine \VRef[Figure]{f:StrSemanticCompare}'s alias state and fragment referent in one API, or at the same time.
|
---|
965 | This section shows the capability in action.
|
---|
966 |
|
---|
967 | \begin{comment}
|
---|
968 | The metaphor of a GUI text-editor is used to illustrate combining these features.
|
---|
969 | Most editors allow selecting a consecutive block of text (highlighted) to define an aliased substring within a document.
|
---|
970 | Typing in this area overwrites the prior text, replacing the selected text with less, same, or more text.
|
---|
971 | Importantly, the document also changes size, not just the selection.
|
---|
972 | %This alias model is assigning to an aliased substring for two strings overlapping by total containment: one is the selected string, the other is the document.
|
---|
973 | Extend the metaphor to two selected areas, where one area can be drag-and-dropped into another, changing the text in the drop area and correspondingly changing the document.
|
---|
974 | When the selected areas are independent, the semantics of the drag-and-drop are straightforward.
|
---|
975 | However, for overlapping selections, either partial or full, there are multiple useful semantics.
|
---|
976 | For example, two areas overlap at the top, or bottom, or a block at a corner, where one areas is dropped into the other.
|
---|
977 | For selecting a smaller area within a larger, and dropping the smaller area into the larger to replace it.
|
---|
978 | In both cases, meaningful semantics must be constructed or the operation precluded.
|
---|
979 | However, without this advanced capability, certain operations become multi-step, possible requiring explicit temporaries.
|
---|
980 | \end{comment}
|
---|
981 |
|
---|
982 | A GUI text-editor provides a metaphor.
|
---|
983 | Selecting a block of text using the mouse defines an aliased substring within a document.
|
---|
984 | Typing in this area overwrites what was there, replacing the originally selected text with more or less text.
|
---|
985 | But the \emph{containing document} also grows or shrinks, not just the selection.
|
---|
986 | This action models assigning to an aliased substring when one string is completely contained in the other.
|
---|
987 |
|
---|
988 | Extend the metaphor to a multi-user editor.
|
---|
989 | If Alice selects a range of text at the bottom, while Bob is rewriting a paragraph at the top, Alice's selection holds onto the characters initially selected, unaffected by Bob making the document grow/shrink even though Alice's start index in the document is changing.
|
---|
990 | This action models assigning to an aliased substring when the two strings do not overlap.
|
---|
991 |
|
---|
992 | Logically, Alice's and Bob's actions on the whole document are like two single-user-edit cases, giving the semantics of the individual edits flowing into a whole.
|
---|
993 | But, there is no need to have two separate document strings.
|
---|
994 | Even if a third selection removes all the text, both Alice's and Bob's strings remain.
|
---|
995 | The independence of their selections assumes that the editor API does not allow the selection to be enlarged, \ie adding text from the containing environment, which may have disappeared.
|
---|
996 |
|
---|
997 | This leaves the ``Venn-diagram overlap'' cases, where Alice's and Bob's selections overlap at the top, bottom, or corner.
|
---|
998 | In this case, the selection areas are dependent, and so, changes in content and size in one may have an affect in the other.
|
---|
999 | There are multiple possible semantics for this case.
|
---|
1000 | The remainder of this section shows the chosen semantics for all of the cases.
|
---|
1001 |
|
---|
1002 | String sharing is expressed using the @`share@ marker to indicate aliasing (mutations shared) \vs snapshot (not quite an immutable result, but one with subsequent mutations isolated).
|
---|
1003 | This aliasing relationship is a sticky property established at initialization.
|
---|
1004 | For example, here strings @s1@ and @s1a@ are in an aliasing relationship, while @s2@ is in a copy relationship.
|
---|
1005 | \input{sharing1.tex}
|
---|
1006 | Here, the aliasing (@`share@) causes partial changes (subscripting) to flow in both directions.
|
---|
1007 | (In the following examples, note how @s1@ and @s1a@ change together, and @s2@ is independent.)
|
---|
1008 | \input{sharing2.tex}
|
---|
1009 | Similarly for complete changes.
|
---|
1010 | \input{sharing3.tex}
|
---|
1011 | Because string assignment copies the value, RHS aliasing is irrelevant.
|
---|
1012 | Hence, aliasing of the LHS is unaffected.
|
---|
1013 | \input{sharing4.tex}
|
---|
1014 |
|
---|
1015 | Now, consider string @s1_mid@ being an alias in the middle of @s1@, along with @s2@, made by a copy from the middle of @s1@.
|
---|
1016 | \input{sharing5.tex}
|
---|
1017 | Again, @`share@ passes changes in both directions; copy does not.
|
---|
1018 | As a result, the index values for the position of @b@ are 1 in the longer string @"abcd"@ and 0 in the shorter aliased string @"bc"@.
|
---|
1019 | This alternate positioning also applies to subscripting.
|
---|
1020 | \input{sharing6.tex}
|
---|
1021 |
|
---|
1022 | Finally, assignment flows through the aliasing relationship without affecting its structure.
|
---|
1023 | \input{sharing7.tex}
|
---|
1024 | In the @"ff"@ assignment, the result is straightforward to accept because the flow direction is from contained (small) to containing (large).
|
---|
1025 | The following rules explain aliasing substrings that flow in the opposite direction, large to small.
|
---|
1026 |
|
---|
1027 | Growth and shrinkage are natural extensions, as for the text-editor analogy, where an empty substring is as real as an empty string.
|
---|
1028 | \input{sharing8.tex}
|
---|
1029 |
|
---|
1030 | Multiple portions of a string can be aliased.
|
---|
1031 | % When there are several aliasing substrings at once, the text editor analogy becomes an online multi-user editor.
|
---|
1032 | %I should be able to edit a paragraph in one place (changing the document's length), without my edits affecting which letters are within a mouse-selection that you had made previously, somewhere else.
|
---|
1033 | \input{sharing9.tex}
|
---|
1034 | When @s1_bgn@'s size increases by 3, @s1_mid@'s starting location moves from 1 to 4 and @s1_end@'s from 3 to 6,
|
---|
1035 |
|
---|
1036 | When changes happen on an aliasing substring that overlap.
|
---|
1037 | \input{sharing10.tex}
|
---|
1038 | Strings @s1_crs@ and @s1_mid@ overlap at character 4, @j@, because the substrings are 3,2 and 4,2.
|
---|
1039 | When @s1_crs@'s size increases by 1, @s1_mid@'s starting location moves from 4 to 5, but the overlapping character remains, changing to @'+'@.
|
---|
1040 |
|
---|
1041 | \PAB{TODO: finish typesetting the demo}
|
---|
1042 |
|
---|
1043 | %\input{sharing-demo.tex}
|
---|
1044 |
|
---|
1045 | \VRef[Figure]{f:ParameterPassing} shows similar relationships when passing the results of substring operations by reference and by value to a subprogram.
|
---|
1046 | Again, notice the side-effects to other reference parameters as one is modified.
|
---|
1047 |
|
---|
1048 | \begin{figure}
|
---|
1049 | \begin{cfa}
|
---|
1050 | // x, a, b, c, & d are substring results passed by reference
|
---|
1051 | // e is a substring result passed by value
|
---|
1052 | void test( string & x, string & a, string & b, string & c, string & d, string e ) {
|
---|
1053 | \end{cfa}
|
---|
1054 | \begin{cquote}
|
---|
1055 | \setlength{\tabcolsep}{2pt}
|
---|
1056 | \begin{tabular}{@{}ll@{}}
|
---|
1057 | \begin{cfa}
|
---|
1058 |
|
---|
1059 | a( 0, 2 ) = "aaa";
|
---|
1060 | b( 1, 12 ) = "bbb";
|
---|
1061 | c( 4, 5 ) = "ccc";
|
---|
1062 | c = "yyy";
|
---|
1063 | d( 0, 3 ) = "ddd";
|
---|
1064 | e( 0, 3 ) = "eee";
|
---|
1065 | x = e;
|
---|
1066 | }
|
---|
1067 | \end{cfa}
|
---|
1068 | &
|
---|
1069 | \sf
|
---|
1070 | \setlength{\extrarowheight}{-0.5pt}
|
---|
1071 | \begin{tabular}{@{}llllll@{}}
|
---|
1072 | x & a & b & c & d & e \\
|
---|
1073 | @"aaaxxxxxxxxx"@ & @"aaax"@ & @"xxx"@ & @"xxxxx"@ & @"xxx"@ & @"xxx"@ \\
|
---|
1074 | @"aaaxbbbxxxxxx"@ & @"aaax"@ & @"xbbb"@ & @"xxxx"@ & @"xxx"@ & @"xxx"@ \\
|
---|
1075 | @"aaaxbbbxxxcccxx"@ & @"aaax"@ & @"xbbb"@ & @"xxxccc"@& @"cccxx"@ & @"xxx"@ \\
|
---|
1076 | @"aaaxbbbyyyxx"@ & @"aaax"@ & @"aaab"@ & @"yyy"@ & @"xx"@ & @"xxx"@ \\
|
---|
1077 | @"aaaxbbbyyyddd"@ & @"aaax"@ & @"xbbb"@ & @"yyy"@ & @"ddd"@ & @"xxx"@ \\
|
---|
1078 | @"aaaxbbbyyyddd"@ & @"aaax"@ & @"xbbb"@ & @"yyy"@ & @"ddd"@ & @"eee"@ \\
|
---|
1079 | @"eee"@ & @""@ & @""@ & @""@ & @"eee"@ \\
|
---|
1080 | & \\
|
---|
1081 | \end{tabular}
|
---|
1082 | \end{tabular}
|
---|
1083 | \end{cquote}
|
---|
1084 | \begin{cfa}
|
---|
1085 | int main() {
|
---|
1086 | string x = "xxxxxxxxxxx";
|
---|
1087 | test( x, x(0, 3), x(2, 3), x(4, 5), x(8, 5), x(8, 5) );
|
---|
1088 | }
|
---|
1089 | \end{cfa}
|
---|
1090 | \caption{Parameter Passing}
|
---|
1091 | \label{f:ParameterPassing}
|
---|
1092 | \end{figure}
|
---|
1093 |
|
---|
1094 |
|
---|
1095 | \section{Storage Management}
|
---|
1096 |
|
---|
1097 | This section discusses issues related to storage management of strings.
|
---|
1098 | Specifically, it is common for strings to logically overlap partially or completely.
|
---|
1099 | \begin{cfa}
|
---|
1100 | string s1 = "abcdef";
|
---|
1101 | string s2 = s1; $\C{// complete overlap, s2 == "abcdef"}$
|
---|
1102 | string s3 = s1.substr( 0, 3 ); $\C{// partial overlap, s3 == "abc"}$
|
---|
1103 | \end{cfa}
|
---|
1104 | This raises the question of how strings behave when an overlapping component is changed,
|
---|
1105 | \begin{cfa}
|
---|
1106 | s3[1] = 'w'; $\C{// what happens to s1 and s2?}$
|
---|
1107 | \end{cfa}
|
---|
1108 | which is restricted by a string's mutable or immutable property.
|
---|
1109 | For example, Java's immutable strings require copy-on-write when any overlapping string changes.
|
---|
1110 | Note, the notion of underlying string mutability is not specified by @const@; \eg in \CC:
|
---|
1111 | \begin{cfa}
|
---|
1112 | const string s1 = "abc";
|
---|
1113 | \end{cfa}
|
---|
1114 | @const@ applies to the @s1@ pointer to @"abc"@, and @"abc"@ is an immutable constant that is \emph{copied} into the string's storage.
|
---|
1115 | Hence, @s1@ is not pointing at an immutable constant and its underlying string is mutable, unless some other designation is specified, such as Java's global immutable rule.
|
---|
1116 |
|
---|
1117 |
|
---|
1118 | \subsection{General Implementation}
|
---|
1119 | \label{string-general-impl}
|
---|
1120 |
|
---|
1121 | A centrepiece of the string module is its memory manager.
|
---|
1122 | The management scheme defines a shared buffer for string text.
|
---|
1123 | Allocation in this buffer is always via a bump-pointer;
|
---|
1124 | the buffer is compacted and/or relocated (to grow) when it fills.
|
---|
1125 | A string is a smart pointer into this buffer.
|
---|
1126 |
|
---|
1127 | This cycle of frequent cheap allocations, interspersed with infrequent expensive compactions, has obvious similarities to a general-purpose memory-manager based on garbage collection (GC).
|
---|
1128 | A few differences are noteworthy.
|
---|
1129 | First, in a general purpose manager, the allocated objects may contain pointers to other objects, making the transitive reachability of these objects a crucial property.
|
---|
1130 | Here, the allocations are text, so one allocation never keeps another alive.
|
---|
1131 | Second, in a general purpose manager, the handle that keeps an allocation alive is a bare pointer.
|
---|
1132 | For strings, a fatter representation is acceptable because this pseudo-pointer is only used for entry into the string-heap, not for general data-substructure linking around the general heap.
|
---|
1133 |
|
---|
1134 | \begin{figure}
|
---|
1135 | \includegraphics{memmgr-basic.pdf}
|
---|
1136 | \caption{String memory-management data structures}
|
---|
1137 | \label{f:memmgr-basic}
|
---|
1138 | \end{figure}
|
---|
1139 |
|
---|
1140 | \VRef[Figure]{f:memmgr-basic} shows the representation.
|
---|
1141 | The heap header and text buffer define a sharing context.
|
---|
1142 | Normally, one global context is appropriate for an entire program;
|
---|
1143 | concurrency is discussed in \VRef{s:ControllingImplicitSharing}.
|
---|
1144 | A string is a handle to a node in a linked list containing a information about a string text in the buffer.
|
---|
1145 | The list is doubly linked for $O(1)$ insertion and removal at any location.
|
---|
1146 | Strings are ordered in the list by text start address.
|
---|
1147 | The heap header maintains a next-allocation pointer, @alloc@, pointing to the last live allocation in the buffer.
|
---|
1148 | No external references point into the buffer and the management procedure relocates the text allocations as needed.
|
---|
1149 | A string handle references a containing string, while its string is contiguous and not null terminated.
|
---|
1150 | The length sets an upper limit on the string size, but is large (4 or 8 bytes).
|
---|
1151 | String handles can be allocated in the stack or heap, and represent the string variables in a program.
|
---|
1152 | Normal C life-time rules apply to guarantee correctness of the string linked-list.
|
---|
1153 | The text buffer is large enough with good management so that often only one dynamic allocation is necessary during program execution, but not so large as to cause program bloat.
|
---|
1154 | % During this period, strings can vary in size dynamically.
|
---|
1155 |
|
---|
1156 | When the text buffer fills, \ie the next new string allocation causes @alloc@ to point beyond the end of the buffer, the strings are compacted.
|
---|
1157 | The linked handles define all live strings in the buffer, which indirectly defines the allocated and free space in the buffer.
|
---|
1158 | The string handles are maintained in sorted order, so the handle list can be traversed, copying the first live text to the start of the buffer, and subsequent strings after each other.
|
---|
1159 | After compaction, if free storage is still be less than the new string allocation, a larger text buffer is heap-allocated, the current buffer is copied into the new buffer, and the original buffer is freed.
|
---|
1160 | Note, the list of string handles is structurally unaffected during a compaction;
|
---|
1161 | only the text pointers in the handles are modified to new buffer locations.
|
---|
1162 |
|
---|
1163 | Object lifecycle events are the \emph{subscription-management} triggers in such a service.
|
---|
1164 | There are two fundamental string-creation functions: importing external text like a C-string or reading a string, and initialization from an existing \CFA string.
|
---|
1165 | When importing, storage comes from the end of the buffer, into which the text is copied.
|
---|
1166 | The new string handle is inserted at the end of the handle list because the new text is at the end of the buffer.
|
---|
1167 | When initializing from text already in the buffer, the new handle is a second reference into the original run of characters.
|
---|
1168 | In this case, the new handle's linked-list position is after the original handle.
|
---|
1169 | Both string initialization styles preserve the string module's internal invariant that the linked-list order matches the buffer order.
|
---|
1170 | For string destruction, handles are removed from the list.
|
---|
1171 | Once the last handle using a run of buffer characters is destroyed, that buffer space is excluded from use until the next compaction.
|
---|
1172 |
|
---|
1173 | Certain string operations result in a substring of another string.
|
---|
1174 | The resulting handle is then placed in the correct sorted position in the list, possible requiring a short linear search to locate the position.
|
---|
1175 | For string operations resulting in a new string, that string is allocated at the end of the buffer.
|
---|
1176 | For shared-edit strings, handles that originally referenced containing locations need to see the new value at the new buffer location.
|
---|
1177 | These strings are moved to appropriate locations at the end of the list \see{details in \VRef{sharing-impl}}.
|
---|
1178 | For nonshared-edit strings, a containing string can be moved and the other strings can remain in the same position.
|
---|
1179 | String assignment works similarly to string initialization, maintaining the invariant of linked-list order matching buffer order.
|
---|
1180 |
|
---|
1181 | At the level of the memory manager, these modifications can always be explained as assignment and appendment.
|
---|
1182 | For example, an append is an assignment into the empty substring at the end of the buffer.
|
---|
1183 | Favourable conditions allow for in-place editing: where there is room for the resulting value in the original buffer location, and where all handles referring to the original buffer location see the new value.
|
---|
1184 | One notable example of favourable conditions occurs because the most recently written string is often the last in the buffer, after which a large amount of free space occurs.
|
---|
1185 | So, repeated appends often occur without copying previously accumulated characters.
|
---|
1186 | However, the general case requires a new buffer allocation: where the new value does not fit in the old place, or if other handles are still using the old value.
|
---|
1187 |
|
---|
1188 |
|
---|
1189 | \subsection{RAII Limitations}
|
---|
1190 | \label{string-raii-limit}
|
---|
1191 |
|
---|
1192 | Earlier work on \CFA~\cite[ch.~2]{Schluntz17} implemented object constructors and destructors for all types (basic and user defined).
|
---|
1193 | A constructor is a user-defined function run implicitly \emph{after} an object's storage is allocated, and a destructor is a user-defined function run \emph{before} an object's storage is deallocated.
|
---|
1194 | This feature, called Resource Acquisition Is Initialization (RAII)~\cite[p.~389]{Stroustrup94}, helps guarantee invariants for users before accessing an object and for the programming environment after an object terminates.
|
---|
1195 |
|
---|
1196 | The purposes of these invariants goes beyond ensuring authentic values inside an object.
|
---|
1197 | Invariants can also track data about managed objects in other data structures.
|
---|
1198 | Reference counting is an example application of an invariant outside of the immediate data value.
|
---|
1199 | With a reference-counting smart-pointer, the constructor and destructor \emph{of a pointer type} track the lifecycle of the object it points to.
|
---|
1200 | Both \CC and \CFA RAII systems are powerful enough to achieve reference counting.
|
---|
1201 |
|
---|
1202 | In general, a lifecycle function has access to an object by location, \ie constructors and destructors receive a @this@ parameter providing an object's memory address.
|
---|
1203 | \begin{cfa}
|
---|
1204 | struct S { int * ip; };
|
---|
1205 | void ?{}( S & @this@ ) { this.ip = new(); } $\C[3in]{// default constructor}$
|
---|
1206 | void ?{}( S & @this@, int i ) { (this){}; *this.ip = i; } $\C{// initializing constructor}$
|
---|
1207 | void ?{}( S & @this@, S s ) { (this){*s.ip}; } $\C{// copy constructor}$
|
---|
1208 | void ^?{}( S & @this@ ) { delete( this.ip ); } $\C{// destructor}\CRT$
|
---|
1209 | \end{cfa}
|
---|
1210 | Such basic examples use the @this@ address only to gain access to the values being managed.
|
---|
1211 | But the lifecycle logic can use the pointer generally, too.
|
---|
1212 | For example, they can add @this@ object to a collection at creation and remove it at destruction.
|
---|
1213 | \begin{cfa}
|
---|
1214 | // header
|
---|
1215 | struct T {
|
---|
1216 | // private
|
---|
1217 | inline dlink(T);
|
---|
1218 | };
|
---|
1219 | void ?{}( T & ); $\C[3in]{// default constructor}$
|
---|
1220 | void ^?{}( T & ); $\C{// destructor}\CRT$
|
---|
1221 | // implementation
|
---|
1222 | static dlist(T) @all_T@;
|
---|
1223 | void ?{}( T & this ) { insert_last(all_T, @this@) }
|
---|
1224 | void ^?{}( T & this ) { remove(this); }
|
---|
1225 | \end{cfa}
|
---|
1226 | A module providing the @T@ type can traverse @all_T@ at relevant times, to keep the objects ``good.''
|
---|
1227 | Hence, declaring a @T@ not only ensures that it begins with an initially ``good'' value, but it also provides an implicit subscription to a service that keeps the value ``good'' during its lifetime.
|
---|
1228 | Again, both \CFA and \CC support this usage style.
|
---|
1229 |
|
---|
1230 | A third capability concerns \emph{implicitly} requested copies.
|
---|
1231 | When stack-allocated objects are used as parameter and return values, a sender's version exists in one stack frame and a receiver's version exists in another.
|
---|
1232 | In the parameter direction, the language's function-call handling must arrange for a copy-constructor call to happen, at a time near the control transfer into the callee. %, with the source as the caller's (sender's) version and the target as the callee's (receiver's) version.
|
---|
1233 | In the return direction, the roles are reversed and the copy-constructor call happens near the return of control.
|
---|
1234 | \CC supports this capability.% without qualification.
|
---|
1235 | \CFA offers limited support;
|
---|
1236 | simple examples work, but implicit copying does not combine successfully with the other RAII capabilities discussed.
|
---|
1237 |
|
---|
1238 | \CC also offers move constructors and return-value optimization~\cite{RVO20}.
|
---|
1239 | These features help reduce unhelpful copy-constructor calls, which, for types like the @S@ example, would lead to extra memory allocations.
|
---|
1240 | \CFA does not currently have these features; adding similarly-intended features to \CFA is desirable.
|
---|
1241 | However, this section is about a problem in the realization of features that \CFA already supports.
|
---|
1242 | Hence, the comparison continues with the classic version of \CC that treated such copy-constructor calls as necessary.
|
---|
1243 |
|
---|
1244 | To summarize the unsupported combinations, the relevant features are:
|
---|
1245 | \begin{enumerate}
|
---|
1246 | \item
|
---|
1247 | Object provider implements lifecycle functions to manage a resource outside of the object.
|
---|
1248 | \item
|
---|
1249 | Object provider implements lifecycle functions to store references back to the object, often originating from outside of it.
|
---|
1250 | \item
|
---|
1251 | Object user expects to pass (in either direction) an object by value for function calls.
|
---|
1252 | \end{enumerate}
|
---|
1253 | \CC supports all three simultaneously. \CFA does not currently support \#2 and \#3 on the same object, though \#1 works along with either one of \#2 or \#3. \CFA needs to be fixed to support all three simultaneously.
|
---|
1254 |
|
---|
1255 | The reason that \CFA does not support \#2 with \#3 is a holdover from how \CFA function calls lowered to C, before \CFA got references and RAII.
|
---|
1256 | At that time, adhering to a principal of minimal intervention, this code could always be treated as passthrough:
|
---|
1257 | \begin{cfa}
|
---|
1258 | struct U { ... };
|
---|
1259 | // RAII to go here
|
---|
1260 | void f( U u ) { F_BODY(u) }
|
---|
1261 | U x;
|
---|
1262 | f( x );
|
---|
1263 | \end{cfa}
|
---|
1264 | But adding custom RAII (at ``...go here'') changes things.
|
---|
1265 | The common \CC lowering~\cite[Sec. 3.1.2.3]{cxx:raii-abi} proceeds differently than the present \CFA lowering.
|
---|
1266 | \begin{cquote}
|
---|
1267 | \setlength{\tabcolsep}{15pt}
|
---|
1268 | \begin{tabular}{@{}l|l@{}}
|
---|
1269 | \begin{cfa}
|
---|
1270 | $\C[0.0in]{// \CC, \CFA future}\CRT$
|
---|
1271 | struct U {...};
|
---|
1272 | // RAII elided
|
---|
1273 | void f( U * __u_orig ) {
|
---|
1274 | U u = * __u_orig; // call copy ctor
|
---|
1275 | F_BODY( u );
|
---|
1276 | // call dtor, u
|
---|
1277 | }
|
---|
1278 | U x; // call default ctor
|
---|
1279 |
|
---|
1280 |
|
---|
1281 | f( &x ) ;
|
---|
1282 |
|
---|
1283 |
|
---|
1284 | // call dtor, x
|
---|
1285 | \end{cfa}
|
---|
1286 | &
|
---|
1287 | \begin{cfa}
|
---|
1288 | $\C[0.0in]{// \CFA today}\CRT$
|
---|
1289 | struct U {...};
|
---|
1290 | // RAII elided
|
---|
1291 | void f( U u ) {
|
---|
1292 |
|
---|
1293 | F_BODY( u );
|
---|
1294 |
|
---|
1295 | }
|
---|
1296 | U x; // call default ctor
|
---|
1297 | {
|
---|
1298 | U __u_for_f = x; // call copy ctor
|
---|
1299 | f( __u_for_f );
|
---|
1300 | // call dtor, __u_for_f
|
---|
1301 | }
|
---|
1302 | // call dtor, x
|
---|
1303 | \end{cfa}
|
---|
1304 | \end{tabular}
|
---|
1305 | \end{cquote}
|
---|
1306 | The current \CFA scheme is still using a by-value C call.
|
---|
1307 | C does a @memcpy@ on structures passed by value.
|
---|
1308 | And so, @F_BODY@ sees the bits of @__u_for_f@ occurring at an address that has never been presented to the @U@ lifecycle functions.
|
---|
1309 | If @U@ is trying to have a style-\#2 invariant, it shows up broken in @F_BODY@: references supposedly to @u@ are actually to @__u_for_f@.
|
---|
1310 | The \CC scheme does not have this problem because it constructs the for @f@ copy in the correct location within @f@.
|
---|
1311 |
|
---|
1312 | Yet, the current \CFA scheme is sufficient to deliver style-\#1 invariants (in this style-\#3 use case) because this scheme still does the correct number of lifecycle calls, using correct values, at correct times.
|
---|
1313 | So, reference-counting or simple ownership applications get their invariants respected under call/return-by-value.
|
---|
1314 |
|
---|
1315 | % [Mike is not currently seeing how distinguishing initialization from assignment is relevant]
|
---|
1316 | % as opposed to assignment where sender and receiver are in the same stack frame.
|
---|
1317 | % What is crucial for lifecycle management is knowing if the receiver is initialized or uninitialized, \ie an object is or is not currently associated with management.
|
---|
1318 | % To provide this knowledge, languages differentiate between initialization and assignment to a left-hand side.
|
---|
1319 | % \begin{cfa}
|
---|
1320 | % Obj obj2 = obj1; $\C[1.5in]{// initialization, obj2 is initialized}$
|
---|
1321 | % obj2 = obj1; $\C{// assignment, obj2 must be initialized for management to work}\CRT$
|
---|
1322 | % \end{cfa}
|
---|
1323 | % Initialization occurs at declaration by value, parameter by argument, return temporary by function call.
|
---|
1324 | % Hence, it is necessary to have two kinds of constructors: by value or object.
|
---|
1325 | % \begin{cfa}
|
---|
1326 | % Obj obj1{ 1, 2, 3 }; $\C[1.5in]{// by value, management is initialized}$
|
---|
1327 | % Obj obj2 = obj1; $\C{// by obj, management is updated}\CRT$
|
---|
1328 | % \end{cfa}
|
---|
1329 | % When no object management is required, initialization copies the right-hand value.
|
---|
1330 | % Hence, the calling convention remains uniform, where the unmanaged case uses @memcpy@ as the initialization constructor and managed uses the specified initialization constructor.
|
---|
1331 |
|
---|
1332 | % [Mike is currently seeing RVO as orthogonal, addressed with the footnote]
|
---|
1333 | % to a temporary.
|
---|
1334 | % For example, in \CC:
|
---|
1335 | % \begin{c++}
|
---|
1336 | % struct S {...};
|
---|
1337 | % S identity( S s ) { return s; }
|
---|
1338 | % S s;
|
---|
1339 | % s = identity( s ); // S temp = identity( s ); s = temp;
|
---|
1340 | % \end{c++}
|
---|
1341 | % the generated code for the function call created a temporary with initialization from the function call, and then assigns the temporary to the object.
|
---|
1342 | % This two step approach means extra storage for the temporary and two copies to get the result into the object variable.
|
---|
1343 | % \CC{17} introduced return value-optimization (RVO)~\cite{RVO20} to ``avoid copying an object that a function returns as its value, including avoiding creation of a temporary object''.
|
---|
1344 | % \CFA uses C semantics for function return giving direct value-assignment, which eliminates unnecessary code, but skips an essential feature needed by lifetime management.
|
---|
1345 | % The following discusses the consequences of this semantics with respect to lifetime management of \CFA strings.
|
---|
1346 |
|
---|
1347 | The string API offers style \#3's pass-by-value in, \eg in the return of @"a" + "b"@.
|
---|
1348 | Its implementation uses the style-\#2 invariant of the string handles being linked to each other, helping to achieve high performance.
|
---|
1349 | Since these two RAII styles cannot coexist, a workaround splits the API into two layers: one that provides pass-by-value, built upon the other with inter-linked handles.
|
---|
1350 | The layer with pass-by-value incurs a performance penalty, while the layer without delivers the desired runtime performance.
|
---|
1351 | The slower, friendlier High Level API (HL, type @string@) wraps the faster, more primitive Low Level API (LL, type @string_res@, abbreviating ``resource'').
|
---|
1352 | Both APIs present the same features, up to return-by-value operations being unavailable in LL and implemented via the workaround in HL.
|
---|
1353 | The intention is for most future code to target HL.
|
---|
1354 | When the RAII issue is fixed, the full HL feature set will be achievable using the LL-style lifetime management.
|
---|
1355 | Then, HL will be removed;
|
---|
1356 | LL's type will be renamed @string@ and programs written for current HL will run faster.
|
---|
1357 | In the meantime, performance-critical sections of applications must use LL.
|
---|
1358 | Subsequent performance experiments \see{\VRef{s:PerformanceAssessment}} use the LL API when comparing \CFA to other languages.
|
---|
1359 | This measurement gives a fair estimate of the goal state for \CFA.
|
---|
1360 | A separate measure of the HL overhead is also included.
|
---|
1361 | hence, \VRef[Section]{string-general-impl} us describing the goal state for \CFA.
|
---|
1362 | In present state, the type @string_res@ replaces its mention of @string@ as inter-linked handle.
|
---|
1363 |
|
---|
1364 | To use LL, a programmer rewrites invocations using pass-by-value APIs into invocations where resourcing is more explicit.
|
---|
1365 | Many invocations are unaffected, notably assignment and comparison.
|
---|
1366 | Of the capabilities listed in \VRef[Figure]{f:StrApiCompare}, only the following three cases need revisions.
|
---|
1367 | \begin{cquote}
|
---|
1368 | \setlength{\tabcolsep}{15pt}
|
---|
1369 | \begin{tabular}{ll}
|
---|
1370 | HL & LL \\
|
---|
1371 | \hline
|
---|
1372 | \begin{cfa}
|
---|
1373 |
|
---|
1374 | string s = "a" + "b";
|
---|
1375 | \end{cfa}
|
---|
1376 | &
|
---|
1377 | \begin{cfa}
|
---|
1378 | string_res sr = "a";
|
---|
1379 | sr += b;
|
---|
1380 | \end{cfa}
|
---|
1381 | \\
|
---|
1382 | \hline
|
---|
1383 | \begin{cfa}
|
---|
1384 | string s = "abcde";
|
---|
1385 | string s2 = s(2, 3); // s2 == "cde"
|
---|
1386 |
|
---|
1387 | s(2,3) = "x"; // s == "abx" && s2 == "cde"
|
---|
1388 | \end{cfa}
|
---|
1389 | &
|
---|
1390 | \begin{cfa}
|
---|
1391 | string_res sr = "abcde";
|
---|
1392 | string_res sr2 = {sr, 2, 3}; // sr2 == "cde"
|
---|
1393 | string_res sr_mid = { sr, 2, 3, SHARE };
|
---|
1394 | sr_mid = "x"; // sr == "abx" && sr2 == "cde"
|
---|
1395 | \end{cfa}
|
---|
1396 | \\
|
---|
1397 | \hline
|
---|
1398 | \begin{cfa}
|
---|
1399 | string s = "abcde";
|
---|
1400 |
|
---|
1401 | s[2] = "xxx"; // s == "abxxxde"
|
---|
1402 | \end{cfa}
|
---|
1403 | &
|
---|
1404 | \begin{cfa}
|
---|
1405 | string_res sr = "abcde";
|
---|
1406 | string_res sr_mid = { sr, 2, 1, SHARE };
|
---|
1407 | mid = "xxx"; // sr == "abxxxde"
|
---|
1408 | \end{cfa}
|
---|
1409 | \end{tabular}
|
---|
1410 | \end{cquote}
|
---|
1411 | The actual HL workaround is having @string@ wrap a pointer to a uniquely owned, heap-allocated @string_res@. This arrangement has @string@ being style-\#1 RAII, which is compatible with pass-by-value.
|
---|
1412 |
|
---|
1413 |
|
---|
1414 | \subsection{Sharing Implementation}
|
---|
1415 | \label{sharing-impl}
|
---|
1416 |
|
---|
1417 | The \CFA string module has two mechanisms to deal with string handles sharing text.
|
---|
1418 | In the first type of sharing, the user requests that both string handles be views of the same logical, modifiable string.
|
---|
1419 | This state is typically produced by the substring operation.
|
---|
1420 | \begin{cfa}
|
---|
1421 | string s = "abcde";
|
---|
1422 | string s1 = s( 1, 2 )@`share@; $\C[2.25in]{// explicit sharing}$
|
---|
1423 | s[1] = 'x'; $\C{// change s and s1}\CRT$
|
---|
1424 | sout | s | s1;
|
---|
1425 | $\texttt{\small axcde xc}$
|
---|
1426 | \end{cfa}
|
---|
1427 | Here, the source string-handle is referencing an entire string, and the resulting, newly made, string handle is referencing a contained portion of the original.
|
---|
1428 | In this state, a modification made in the overlapping area is visible in both strings.
|
---|
1429 |
|
---|
1430 | The second type of sharing happens when the system implicitly delays the physical execution of a logical \emph{copy} operation, as part of its copy-on-write optimization.
|
---|
1431 | This state is typically produced by constructing a new string, using an original string as its initialization source.
|
---|
1432 | \begin{cfa}
|
---|
1433 | string s = "abcde";
|
---|
1434 | string s1 = s( 1, 2 )@@; $\C[2.25in]{// no sharing}$
|
---|
1435 | s[1] = 'x'; $\C{// copy-on-write s1}\CRT$
|
---|
1436 | sout | s | s1;
|
---|
1437 | $\texttt{\small axcde bc}$
|
---|
1438 | \end{cfa}
|
---|
1439 | In this state, a subsequent modification done on one handle triggers the deferred copy action, leaving the handles referencing different text within the buffer, holding distinct values.
|
---|
1440 |
|
---|
1441 | A further abstraction helps distinguish the two senses of sharing.
|
---|
1442 | A share-edit set (SES) is an equivalence class over string handles, being the reflexive, symmetric and transitive closure of the relationship of one string being constructed from another, with the ``share'' option given.
|
---|
1443 | The SES is represented by a second linked list among the handles.
|
---|
1444 | A string that shares edits with no other is in a SES by itself.
|
---|
1445 | Inside a SES, a logical modification of one substring portion may change the logical value in another substring portion, depending on whether the two actually overlap.
|
---|
1446 | Conversely, no logical value change can flow outside of a SES.
|
---|
1447 | Even if a modification on one string handle does not reveal itself \emph{logically} to anther handle in the same SES (because they do not overlap), if the modification is length-changing, completing the modification requires visiting the second handle to adjust its location in the sliding text.
|
---|
1448 |
|
---|
1449 |
|
---|
1450 | \subsection{Controlling Implicit Sharing}
|
---|
1451 | \label{s:ControllingImplicitSharing}
|
---|
1452 |
|
---|
1453 | There are tradeoffs associated with sharing and its implicit copy-on-write mechanism.
|
---|
1454 | Several qualitative matters are detailed in \VRef{s:PerformanceAssessment}.
|
---|
1455 | In detail, string sharing has inter-linked string handles, so managing one string is also managing the neighbouring strings, and from there, a data structure of the ``set of all strings.''
|
---|
1456 | Therefore, it is useful to toggle this capability on or off when it is not providing any application benefit.
|
---|
1457 |
|
---|
1458 | The \CFA string library provides the type @string_sharectx@ to control an ambient sharing context.
|
---|
1459 | It allows two adjustments: to opt out of sharing entirely or to begin sharing within a private context.
|
---|
1460 | Running with sharing disabled can be thought of as a \CC STL-emulation mode, where each string is dynamically allocated.
|
---|
1461 | The chosen mode applies for the duration of the lifetime of the created @string_sharectx@ object, up to being suspended by child lifetimes of different contexts.
|
---|
1462 | \VRef[Figure]{fig:string-sharectx} illustrates this behaviour by showing the stack frames of a program in execution.
|
---|
1463 | In this example, the single-letter functions are called in alphabetic order.
|
---|
1464 | The functions @a@, @b@ and @g@ share string character ranges with each other, because they occupy a common sharing-enabled context.
|
---|
1465 | The function @e@ shares within itself (because its is in a sharing-enabled context), but not with the rest of the program (because its context is not occupied by any of the rest of the program).
|
---|
1466 | The functions @c@, @d@ and @f@ never share anything, because they are in a sharing-disabled context.
|
---|
1467 | Executing the example does not produce an interesting outcome, but the comments in the picture indicate when the logical copy operation runs with
|
---|
1468 | \begin{description}
|
---|
1469 | \item[share:] the copy being deferred, as described through the rest of this section (fast), or
|
---|
1470 | \item[copy:] the copy performed eagerly (slow).
|
---|
1471 | \end{description}
|
---|
1472 | Only eager copies can cross @string_sharectx@ boundaries.
|
---|
1473 | The intended use is with stack-managed lifetimes, in which the established context lasts until the current function returns, and affects all functions called that do not create their own contexts.
|
---|
1474 |
|
---|
1475 | \begin{figure}
|
---|
1476 | \begin{tabular}{ll}
|
---|
1477 | \lstinputlisting[language=CFA, firstline=10, lastline=55]{sharectx.run.cfa}
|
---|
1478 | &
|
---|
1479 | \raisebox{-0.17\totalheight}{\includegraphics{string-sharectx.pdf}} % lower
|
---|
1480 | \end{tabular}
|
---|
1481 | \caption{Controlling copying vs sharing of strings using \lstinline{string_sharectx}.}
|
---|
1482 | \label{fig:string-sharectx}
|
---|
1483 | \end{figure}
|
---|
1484 |
|
---|
1485 |
|
---|
1486 | \subsection{Sharing and Threading}
|
---|
1487 |
|
---|
1488 | The \CFA string library provides no thread safety, the same as \CC string, providing similar performance goals.
|
---|
1489 | Threads can create their own string buffers and avoid passing these strings to other threads, or require that shared strings be immutable, as concurrent reading is safe.
|
---|
1490 | A positive consequence of this approach is that independent threads can use the sharing buffer without locking overhead.
|
---|
1491 | When string sharing amongst threads is required, program-wide string-management can toggled to non-sharing using @malloc@/@free@, where the storage allocator is assumed to be thread-safe.
|
---|
1492 | Finally, concurrent users of string objects can provide their own mutual exclusion.
|
---|
1493 |
|
---|
1494 |
|
---|
1495 | \subsection{Short-String Optimization}
|
---|
1496 |
|
---|
1497 | \CC implements a short-string ($\le$16) optimization (SSO).
|
---|
1498 | As a string header contains a pointer to the string text, this pointer can be tagged and used to contain a short string, removing a dynamic memory allocation/deallocation.
|
---|
1499 | \begin{c++}
|
---|
1500 | class string {
|
---|
1501 | union {
|
---|
1502 | struct { $\C{// long string, text in heap}$
|
---|
1503 | size_t size;
|
---|
1504 | char * strptr;
|
---|
1505 | } lstr;
|
---|
1506 | char sstr[sizeof(lstr)]; $\C{// short string <16 characters, text in situ}$
|
---|
1507 | };
|
---|
1508 | // some tagging for short or long strings
|
---|
1509 | };
|
---|
1510 | \end{c++}
|
---|
1511 | However, there is now a conditional check required on the fast-path to switch between short and long string operations.
|
---|
1512 |
|
---|
1513 | It might be possible to pack 16- or 32-bit Unicode characters within the same string buffer as 8-bit characters.
|
---|
1514 | Again, locations for identification flags must be found and checked along the fast path to select the correct actions.
|
---|
1515 | Handling utf8 (variable length), is more problematic because simple pointer arithmetic cannot be used to stride through the variable-length characters.
|
---|
1516 | Trying to use a secondary array of fixed-sized pointers/offsets to the characters is possible, but raises the question of storage management for the utf8 characters themselves.
|
---|
1517 |
|
---|
1518 |
|
---|
1519 | \section{Performance Assessment}
|
---|
1520 | \label{s:PerformanceAssessment}
|
---|
1521 |
|
---|
1522 | I assessed the \CFA string library's speed and memory usage against strings in \CC STL.
|
---|
1523 | Overall, this analysis shows that adding support for the features shown earlier in the chapter comes at no substantial cost in the performance of features common to both APIs.
|
---|
1524 |
|
---|
1525 | Moreover, the results support the \CFA string's position as a high-level enabler of simplified text processing.
|
---|
1526 | STL makes its user think about memory management.
|
---|
1527 | When the user does, and is successful, STL's performance can be very good.
|
---|
1528 | But when the user fails to think through the consequences of the STL representation, performance becomes poor.
|
---|
1529 | The \CFA string lets the user work at the level of just putting the right text into the right variables, with corresponding performance degradations reduced or eliminated.
|
---|
1530 |
|
---|
1531 | % The final test shows the overall win of the \CFA text-sharing mechanism.
|
---|
1532 | % It exercises several operations together, showing \CFA enabling clean user code to achieve performance that STL requires less-clean user code to achieve.
|
---|
1533 |
|
---|
1534 |
|
---|
1535 | \subsection{Methodology}
|
---|
1536 |
|
---|
1537 | These tests use a \emph{corpus} of strings.
|
---|
1538 | Their lengths are important; the specific characters occurring in them are immaterial.
|
---|
1539 | In a result graph, a corpus's mean string length is often the independent variable shown on the X axis.
|
---|
1540 |
|
---|
1541 | When a corpus contains strings of different lengths, the lengths are drawn from a lognormal distribution.
|
---|
1542 | Therefore, strings much longer than the mean occur less often and strings slightly shorter than the mean occur most often.
|
---|
1543 | A corpus's string sizes are one of:
|
---|
1544 | \begin{description}
|
---|
1545 | \item [Fixed-size] all string lengths are of the stated size.
|
---|
1546 | \item [Varying 1 and up] the string lengths are drawn from the lognormal distribution with a stated mean and all lengths occur.
|
---|
1547 | \item [Varying 16 and up] string lengths are drawn from the lognormal distribution with the stated mean, but only lengths 16 and above occur; thus, the stated mean is above 16.
|
---|
1548 | \end{description}
|
---|
1549 | The special treatment of length 16 deals with the SSO in STL @string@, currently not implemented in \CFA.
|
---|
1550 | A fixed-size or from-16 distribution ensures that \CC's extra-optimized cases are isolated within, or removed from, the comparison.
|
---|
1551 | In all experiments that use a corpus, its text is generated and loaded into the system under test before the timed phase begins.
|
---|
1552 | To ensure comparable results, a common memory allocator is used for \CFA and \CC.
|
---|
1553 | \CFA runs the llheap allocator~\cite{Zulfiqar22}, which is also plugged into \CC.
|
---|
1554 |
|
---|
1555 | The operations being measured take dozens of nanoseconds, so a succession of many invocations is run and timed as a group.
|
---|
1556 | The experiments run for a fixed duration (5 seconds), as determined by re-checking @clock()@ every 10,000 invocations, which is never more often than once per 80 ms.
|
---|
1557 | Timing outcomes report mean nanoseconds per invocation, which includes harness overhead and the targeted string API execution.
|
---|
1558 |
|
---|
1559 | As discussed in \VRef[Section]{string-raii-limit}, general performance comparisons are made using \CFA's faster, low-level string API, named @string_res@.
|
---|
1560 | \VRef{s:ControllingImplicitSharing} presents an operational mode where \CFA string sharing is turned off.
|
---|
1561 | In this mode, the \CFA string operates similarly to \CC's, by using a heap allocation for string text.
|
---|
1562 | Some experiments include measurements in this mode for baselining purposes, called ``\CC emulation mode'' or ``nosharing''.
|
---|
1563 |
|
---|
1564 | See~\VRef{s:ExperimentalEnvironment} for a description of the hardware environment.
|
---|
1565 |
|
---|
1566 |
|
---|
1567 | \subsection{Test: Append}
|
---|
1568 |
|
---|
1569 | These tests measure the speed of appending strings from the corpus onto a larger, growing string.
|
---|
1570 | They show \CFA performing comparably to \CC overall, though with penalties for simple API misuses.
|
---|
1571 | The basic harness is:
|
---|
1572 | \begin{cfa}
|
---|
1573 | // set alarm duration
|
---|
1574 | for ( ... ) { $\C[1.5in]{// loop for duration}$
|
---|
1575 | for ( i; N ) { $\C{// perform multiple appends (concatenations)}$
|
---|
1576 | accum += corpus[ f( i ) ];
|
---|
1577 | }
|
---|
1578 | count += N; $\C{// count number of appends}\CRT$
|
---|
1579 | }
|
---|
1580 | \end{cfa}
|
---|
1581 | The harness's outer loop executes for the experiment duration.
|
---|
1582 | The string is reset to empty before appending (not shown).
|
---|
1583 | The inner loop builds up a growing-length string with successive appends.
|
---|
1584 | Each run targets a specific (mean) corpus string length and produces one data point on the result graph.
|
---|
1585 | Three specific comparisons are made with this harness.
|
---|
1586 | Each picks its own independent-variable basis of comparison.
|
---|
1587 | All three comparisons use the varying-from-1 corpus construction, \ie they allow the STL to show its advantage for SSO.
|
---|
1588 |
|
---|
1589 |
|
---|
1590 | \subsubsection{Fresh vs Reuse in \CC, Emulation Baseline}
|
---|
1591 |
|
---|
1592 | The first experiment compares \CFA with \CC, with \CFA operating in nosharing mode and \CC having no other mode, hence both string package are using @malloc@/@free@.
|
---|
1593 | % This experiment establishes a baseline for other experiments.
|
---|
1594 | This experiment also introduces the first \CC coding pitfall, which the next experiment shows is helped by turning on \CFA sharing.
|
---|
1595 | % This pitfall shows, a \CC programmer must pay attention to string variable reuse.
|
---|
1596 | In the following, both programs are doing the same thing: start with @accum@ empty and build it up by appending @N@ strings (type @string@ in \CC and the faster @string_res@ in \CFA).
|
---|
1597 | \begin{cquote}
|
---|
1598 | \setlength{\tabcolsep}{40pt}
|
---|
1599 | \begin{tabular}{@{}ll@{}}
|
---|
1600 | % \multicolumn{1}{c}{\textbf{fresh}} & \multicolumn{1}{c}{\textbf{reuse}} \\
|
---|
1601 | \begin{cfa}
|
---|
1602 |
|
---|
1603 | for ( ... ) {
|
---|
1604 | @string_res accum;@ $\C[1.5in]{// fresh}$
|
---|
1605 | for ( N )
|
---|
1606 | accum @+=@ ... $\C{// append}\CRT$
|
---|
1607 | }
|
---|
1608 | \end{cfa}
|
---|
1609 | &
|
---|
1610 | \begin{cfa}
|
---|
1611 | string_res accum;
|
---|
1612 | for ( ... ) {
|
---|
1613 | @accum = "";@ $\C[1.5in]{// reuse}$
|
---|
1614 | for ( N )
|
---|
1615 | accum @+=@ ... $\C{// append}\CRT$
|
---|
1616 | }
|
---|
1617 | \end{cfa}
|
---|
1618 | \end{tabular}
|
---|
1619 | \end{cquote}
|
---|
1620 | The difference is creating a new or reusing an existing string variable.
|
---|
1621 | The pitfall is that most programmers do not consider this difference.
|
---|
1622 | However, creating a new variable implies deallocating the previous string storage and allocating new empty storage.
|
---|
1623 | As the string grows, further deallocations/allocations are required to release the previous and extend the current string storage.
|
---|
1624 | So, the fresh version is constantly restarting with zero string storage, while the reuse version benefits from having its prior large storage from the last append sequence.
|
---|
1625 |
|
---|
1626 | \begin{figure}
|
---|
1627 | \centering
|
---|
1628 | \includegraphics{plot-string-peq-cppemu.pdf}
|
---|
1629 | % \includegraphics[width=\textwidth]{string-graph-peq-cppemu.png}
|
---|
1630 | \caption{Fresh vs Reuse in \CC, Emulation Baseline.
|
---|
1631 | Average time per iteration with one \lstinline{x += y} invocation (lower is better).
|
---|
1632 | Comparing \CFA's STL emulation mode with STL implementations, and comparing the fresh with reused reset styles.}
|
---|
1633 | \label{fig:string-graph-peq-cppemu}
|
---|
1634 | \bigskip
|
---|
1635 | \bigskip
|
---|
1636 | \includegraphics{plot-string-peq-sharing.pdf}
|
---|
1637 | % \includegraphics[width=\textwidth]{string-graph-peq-sharing.png}
|
---|
1638 | \caption{\CFA Compromise for Fresh \vs Reuse.
|
---|
1639 | Average time per iteration with one \lstinline{x += y} invocation (lower is better).
|
---|
1640 | Comparing \CFA's sharing mode with STL, and comparing the fresh with reused reset styles.
|
---|
1641 | The \CC results are repeated from \VRef[Figure]{fig:string-graph-peq-cppemu}.}
|
---|
1642 | \label{fig:string-graph-peq-sharing}
|
---|
1643 | \end{figure}
|
---|
1644 |
|
---|
1645 | \VRef[Figure]{fig:string-graph-peq-cppemu} shows the resulting performance.
|
---|
1646 | The two fresh (solid) lines and the two reuse (dash) lines are identical, except for lengths $\le$10, where the \CC SSO has a 40\% average and minimally 24\% advantage.
|
---|
1647 | The gap between the fresh and reuse lines is the removal of the dynamic memory allocates and reuse of prior storage, \eg 100M allocations for fresh \vs 100 allocations for reuse across all experiments.
|
---|
1648 | While allocation reduction is huge, data copying dominates the cost, so the lines are still reasonably close together.
|
---|
1649 |
|
---|
1650 |
|
---|
1651 | \subsubsection{\CFA's Sharing Mode}
|
---|
1652 |
|
---|
1653 | This comparison is the same as the last one, except the \CFA implementation is using sharing mode.
|
---|
1654 | Hence, both \CFA's fresh and reuse versions have no memory allocations, and as before, only for reuse does \CC have no memory allocations.
|
---|
1655 | \VRef[Figure]{fig:string-graph-peq-sharing} shows the resulting performance.
|
---|
1656 | For fresh at append lengths 5 and above, \CFA is now closer to the \CC reuse performance, because of removing the dynamic allocations.
|
---|
1657 | However, for reuse, \CFA has slowed down slightly, to performance matching the new fresh version, as the two versions are now implemented virtually the same.
|
---|
1658 | The reason for the \CFA reuse slow-down is the overhead of managing the sharing scheme (primarily maintaining the list of handles), without gaining any benefit.
|
---|
1659 |
|
---|
1660 | \begin{comment}
|
---|
1661 | FIND A HOME!!!
|
---|
1662 | The potential benefits of the sharing scheme do not give \CFA an edge over \CC when appending onto a reused string, though the first one helps \CFA win at going onto a fresh string. These abilities are:
|
---|
1663 | \begin{itemize}
|
---|
1664 | \item
|
---|
1665 | To grow a text allocation repeatedly without copying it elsewhere.
|
---|
1666 | This ability is enabled by \CFA's most-recently modified string being located immediately before the text buffer's \emph{shared} bump-pointer area, \ie often a very large greenfield, relative to the \emph{individual} string being grown.
|
---|
1667 | With \CC-reuse, this benefit is already reaped by the user's reuse of a pre-stretched allocation.
|
---|
1668 | Yet \CC-fresh pays the higher cost because its room to grow for free is at most a constant times the original string's length.
|
---|
1669 | \item
|
---|
1670 | To share an individual text allocation across multiple related strings.
|
---|
1671 | This ability is not applicable to appending with @+=@.
|
---|
1672 | It in play in [xref sub-experiment pta] and [xref experiment pbv].
|
---|
1673 | \item
|
---|
1674 | To share a text arena across unrelated strings, sourcing disparate allocations from a common place.
|
---|
1675 | That is, always allocating from a bump pointer, and never maintaining free lists.
|
---|
1676 | This ability is not relevant to running any append scenario on \CFA with sharing, because appending modifies an existing allocation and is not driving several allocations.
|
---|
1677 | This ability is assessed in [xref experiment allocn].
|
---|
1678 | \end{itemize}
|
---|
1679 | This cost, of slowing down append-with-reuse, is \CFA paying the piper for other scenarios done well.
|
---|
1680 | \CFA prioritizes the fresh use case because it is more natural.
|
---|
1681 | The \emph{user-invoked} reuse scheme is an unnatural programming act because it deliberately misuses lexical scope: a variable (@accum@) gets its lifetime extended beyond the scope in which it is used.
|
---|
1682 |
|
---|
1683 | A \CFA user needing the best performance on an append scenario can still access the \CC-like speed by invoking noshare.
|
---|
1684 | This (indirect) resource management is memory-safe, as compared to that required in \CC to use @string&@, where knowledge of another string's lifetime comes into play.
|
---|
1685 | This abstraction opt-out is also different from invoking the LL API-level option.
|
---|
1686 | In fact, these considerations are orthogonal.
|
---|
1687 | But the key difference is that invoking the LL API would be a temporary measure, to use a workaround of a known \CFA language issue; choosing to exempt a string from sharing is a permanent act of program tuning.
|
---|
1688 | Beyond these comparisons, opting for noshare actually provides program ``eye candy,'' indicating that under-the-hood thinking is becoming relevant here.
|
---|
1689 | \end{comment}
|
---|
1690 |
|
---|
1691 |
|
---|
1692 | \subsubsection{Misusing Concatenation}
|
---|
1693 |
|
---|
1694 | A further pitfall occurs writing the apparently equivalent @x = x + y@ \vs @x += y@.
|
---|
1695 | For numeric types, the generated code is equivalent, giving identical performance.
|
---|
1696 | However, for string types there can be a significant difference.
|
---|
1697 | This pitfall is a particularly likely for beginners.
|
---|
1698 |
|
---|
1699 | In earlier experiments, the choice of \CFA API among HL and LL had no impact on the functionality being tested.
|
---|
1700 | Here, however, the @+@ operation, which returns its result by value, is only available in HL.
|
---|
1701 | The \CFA @+@ number was obtained by inlining the HL implementation of @+@, which is done using LL's @+=@, into the test harness, while omitting the HL-inherent extra dynamic allocation. The HL-upon-LL @+@ implementation, is:
|
---|
1702 | \begin{cfa}
|
---|
1703 | struct string {
|
---|
1704 | string_res * inner; // RAII manages malloc/free, simple ownership
|
---|
1705 | };
|
---|
1706 | void ?+=?( string & s, string s2 ) {
|
---|
1707 | (*s.inner) += (*s2.inner);
|
---|
1708 | }
|
---|
1709 | string @?+?@( string lhs, string rhs ) {
|
---|
1710 | string ret = lhs;
|
---|
1711 | ret @+=@ rhs;
|
---|
1712 | return ret;
|
---|
1713 | }
|
---|
1714 | \end{cfa}
|
---|
1715 | This @+@ implementation is also the goal implementation of @+@ once the HL/LL workaround is no longer needed. Inlining the induced LL steps into the test harness gives:
|
---|
1716 | \begin{cquote}
|
---|
1717 | \setlength{\tabcolsep}{20pt}
|
---|
1718 | \begin{tabular}{@{}ll@{}}
|
---|
1719 | \multicolumn{1}{c}{\textbf{Goal}} & \multicolumn{1}{c}{\textbf{Measured}} \\
|
---|
1720 | \begin{cfa}
|
---|
1721 |
|
---|
1722 | for ( ... ) {
|
---|
1723 | string accum;
|
---|
1724 | for ( ... ) {
|
---|
1725 | accum = @accum + ...@
|
---|
1726 |
|
---|
1727 |
|
---|
1728 | }
|
---|
1729 | }
|
---|
1730 | \end{cfa}
|
---|
1731 | &
|
---|
1732 | \begin{cfa}
|
---|
1733 | string_res pta_ll_temp;
|
---|
1734 | for ( ... ) {
|
---|
1735 | string_res accum;
|
---|
1736 | for ( ... ) {
|
---|
1737 | pta_ll_temp = @accum@;
|
---|
1738 | pta_ll_temp @+= ...@;
|
---|
1739 | accum = pta_ll_temp;
|
---|
1740 | }
|
---|
1741 | }
|
---|
1742 | \end{cfa}
|
---|
1743 | \end{tabular}
|
---|
1744 | \end{cquote}
|
---|
1745 | Note, the goal code functions today in HL but with slower performance.
|
---|
1746 |
|
---|
1747 | \begin{figure}
|
---|
1748 | \centering
|
---|
1749 | \includegraphics{plot-string-pta-sharing.pdf}
|
---|
1750 | % \includegraphics[width=\textwidth]{string-graph-pta-sharing.png}
|
---|
1751 | \caption{CFA's low overhead for misusing concatenation. Average time per iteration with one \lstinline{x += y} invocation (lower is better). Comparing \CFA (having implicit sharing activated) with STL, and comparing the \lstinline{+}-then-\lstinline{=} with the \lstinline{+=} append styles. The \lstinline{+=} results are repeated from \VRef[Figure]{fig:string-graph-peq-sharing}.}
|
---|
1752 | \label{fig:string-graph-pta-sharing}
|
---|
1753 | \end{figure}
|
---|
1754 |
|
---|
1755 | \VRef[Figure]{fig:string-graph-pta-sharing} gives the outcome, where the Y-axis is log scale because of the large differences.
|
---|
1756 | The STL's penalty is $8 \times$ while \CFA's is only $2 \times$, averaged across the cases shown here.
|
---|
1757 | Moreover, the STL's gap increases with string size, while \CFA's converges.
|
---|
1758 | So again, \CFA helps users who just want to treat strings as values, and not think about the resource management under the covers.
|
---|
1759 |
|
---|
1760 | While not a design goal, and not graphed, \CFA in STL-emulation mode outperformed STL in this case.
|
---|
1761 | User-managed allocation reuse did not affect either implementation in this case; only ``fresh'' results are shown.
|
---|
1762 |
|
---|
1763 |
|
---|
1764 | \subsection{Test: Pass Argument}
|
---|
1765 |
|
---|
1766 | STL has a penalty for passing a string by value, which forces users to think about memory management when communicating values with a function.
|
---|
1767 | The key \CFA value-add is that a user can think of a string simply as a value; this test shows that \CC charges a stiff penalty for thinking this way, while \CFA does not.
|
---|
1768 | This test illustrates a main advantage of the \CFA sharing algorithm (in one case).
|
---|
1769 | It shows STL's SSO providing a successful mitigation (in the other case).
|
---|
1770 |
|
---|
1771 | The basic operation considered is:
|
---|
1772 | \begin{cfa}
|
---|
1773 | void foo( string s );
|
---|
1774 | string s = "abc";
|
---|
1775 | foo( s );
|
---|
1776 | \end{cfa}
|
---|
1777 | With implicit sharing active, \CFA treats this operation as normal and supported.
|
---|
1778 |
|
---|
1779 | Again, an HL-LL difference requires an LL mockup. This time, the fact to integrate into the test harness is that LL does not directly support pass-by-value.
|
---|
1780 | \begin{cquote}
|
---|
1781 | \setlength{\tabcolsep}{20pt}
|
---|
1782 | \begin{tabular}{@{}ll@{}}
|
---|
1783 | \multicolumn{1}{c}{\textbf{Goal}} & \multicolumn{1}{c}{\textbf{Measured}} \\
|
---|
1784 | \begin{cfa}
|
---|
1785 | void helper( string q ) {
|
---|
1786 |
|
---|
1787 | }
|
---|
1788 | for ( ... ) { // loop for duration
|
---|
1789 | helper( corpus[ f( i ) ] );
|
---|
1790 | count += 1;
|
---|
1791 | }
|
---|
1792 | \end{cfa}
|
---|
1793 | &
|
---|
1794 | \begin{cfa}
|
---|
1795 | void helper( string_res & qref ) {
|
---|
1796 | string_res q = { qref, COPY_VALUE };
|
---|
1797 | }
|
---|
1798 |
|
---|
1799 |
|
---|
1800 |
|
---|
1801 |
|
---|
1802 | \end{cfa}
|
---|
1803 | \end{tabular}
|
---|
1804 | \end{cquote}
|
---|
1805 | The goal (HL) version gives the modified test harness, with a single loop.
|
---|
1806 | Each iteration uses a corpus item as the argument to the function call.
|
---|
1807 | These corpus items were imported to the string heap before beginning the timed run.
|
---|
1808 |
|
---|
1809 | \begin{figure}
|
---|
1810 | \centering
|
---|
1811 | \includegraphics{plot-string-pbv.pdf}
|
---|
1812 | % \includegraphics[width=\textwidth]{string-graph-pbv.png}
|
---|
1813 | \begin{tabularx}{\linewidth}{>{\centering\arraybackslash}X >{\centering\arraybackslash}X} (a) & (b) \end{tabularx}
|
---|
1814 | \caption{Average time per iteration (lower is better) with one call to a function that takes a by-value string argument, comparing \CFA (having implicit sharing activated) with STL.
|
---|
1815 | (a) With \emph{Varying 1 and up} corpus construction, in which the STL-only benefit of SSO optimization occurs, in varying degrees, at all string sizes.
|
---|
1816 | (b) With \emph{Fixed-size} corpus construction, in which this benefit applies exactly to strings with length below 16.}
|
---|
1817 | \label{fig:string-graph-pbv}
|
---|
1818 | \end{figure}
|
---|
1819 |
|
---|
1820 | \VRef[Figure]{fig:string-graph-pbv} shows the costs for calling a function that receives a string argument by value.
|
---|
1821 | STL's performance worsens uniformly as string length increases, while \CFA has the same performance at all sizes.
|
---|
1822 | Although the STL is better than \CFA until string length 10 because of the SSO.
|
---|
1823 | While improved, the \CFA cost to pass a string is still nontrivial.
|
---|
1824 | The contributor is adding and removing the callee's string handle from the global list.
|
---|
1825 | This cost is $1.5 \times$ to $2 \times$ over STL's when SSO applies, but is avoidable once \CFA realizes this optimization.
|
---|
1826 | At the larger sizes, the STL runs more than $3 \times$ slower, because it has to allocation/deallocate storage for the parameter and copy the argument string to the parameter.
|
---|
1827 | If the \CC string is passed by reference, the results are better and flat across string lengths like \CFA.
|
---|
1828 |
|
---|
1829 |
|
---|
1830 | \subsection{Test: Allocate}
|
---|
1831 |
|
---|
1832 | This test directly compares the allocation schemes of the \CFA string (sharing active), with the STL string.
|
---|
1833 | It treats the \CFA scheme as a form of garbage collection (GC), and the STL scheme as an application of malloc-free.
|
---|
1834 | The test shows that \CFA enables faster speed in exchange for greater memory usage.
|
---|
1835 |
|
---|
1836 | A precise garbage-collector, which knows all pointers and may modify them, often runs faster than malloc-free in an amortized analysis, even though it must occasionally stop to collect (latency issues).
|
---|
1837 | The speedup happens indirectly because GC is able to move objects.
|
---|
1838 | (In the case of the mini-allocator powering the \CFA string library, objects are runs of text.)
|
---|
1839 | Moving objects creates a large contiguous store of available memory;
|
---|
1840 | fresh allocations consume from this area using light-weight \emph{bump-allocation}.
|
---|
1841 | A malloc-free implementation cannot move objects because the location of allocated objects is unknown;
|
---|
1842 | hence, free-space management is more complex managing linked structures of freed allocations and possibly coalescing freed blocks.
|
---|
1843 |
|
---|
1844 | GC occurs lazily, so the lifetime of unreachable allocations is unknown, \eg GC may never be triggered.
|
---|
1845 | A garbage collector can minimize the memory footprint for unreachable allocations by collecting eagerly.
|
---|
1846 | However, this approach can negate GC's speed advantage.
|
---|
1847 | Alternatively, collecting infrequently can consume large amounts of resident and virtual memory.
|
---|
1848 | In contrast, a program using malloc-free tries to release an allocation as soon as it is unreachable.
|
---|
1849 | This approach reduces the memory footprint (depending on the allocator), but has a per allocation cost for each free.
|
---|
1850 | % [TODO: find citations for the above knowledge]
|
---|
1851 | Therefore, a speed \vs memory tradeoff is a good comparator for \CFA--STL string allocations.
|
---|
1852 | %The test verifies that it is so and quantifies the returns available.
|
---|
1853 |
|
---|
1854 | These tests manipulate a tuning knob that controls how much extra space to use.
|
---|
1855 | Specific values of this knob are not user-visible and are not presented in the results.
|
---|
1856 | Instead, its two effects (amount of space used and time per operation) are shown.
|
---|
1857 | The independent variable is the liveness target, which is the fraction of the text buffer in use at the end of a collection.
|
---|
1858 | The allocator expands its text buffer during a collection if the actual live fraction exceeds this target.
|
---|
1859 |
|
---|
1860 | \begin{figure}
|
---|
1861 | \centering
|
---|
1862 | \includegraphics{string-perf-alloc.pdf}
|
---|
1863 | \caption{Memory-allocation test's harness and its resulting pattern of memory usage under a bump-pointer-only scheme.}
|
---|
1864 | \label{fig:string-perf-alloc}
|
---|
1865 | \end{figure}
|
---|
1866 |
|
---|
1867 | \VRef[Figure]{fig:string-perf-alloc} shows the memory-allocation pattern that the test harness drives.
|
---|
1868 | Note how this pattern creates few long-lived strings and many short-lived strings.
|
---|
1869 | To extend this pattern to the scale of a performance test, the harness is actually recursive, to achieve the nesting (three levels in the figure), and iterative, to achieve the fan-out (factor two / binary tree in the figure).
|
---|
1870 | \begin{cfa}
|
---|
1871 | void f( int depth ) {
|
---|
1872 | if (depth == 0) return;
|
---|
1873 | string_res x = corpus[...]; // importing from char * here
|
---|
1874 | COUNT_ONE_OP_DONE
|
---|
1875 | for ( fanOut ) {
|
---|
1876 | // elided: terminate fixed-duration experiment
|
---|
1877 | f( depth - 1 );
|
---|
1878 | }
|
---|
1879 | }
|
---|
1880 | START_TIMER
|
---|
1881 | f( launchDepth );
|
---|
1882 | STOP_TIMER
|
---|
1883 | \end{cfa}
|
---|
1884 | The runs presented use a call depth of 1000 and a fan-out of 1.006, which means that approximately one call in 167 makes two recursive calls, while the rest make one.
|
---|
1885 | This sizing keeps an average of 836 strings live and keeps the amounts of consumed memory within the machine's last-level cache.
|
---|
1886 | The time measurement is nanoseconds per @f@-call, for internal or leaf strings.
|
---|
1887 |
|
---|
1888 | % String lifetime (measured in number of subsequent string allocations) is ?? distributed, because each node in the call tree survives as long as its descendent calls.
|
---|
1889 |
|
---|
1890 |
|
---|
1891 | \begin{figure}
|
---|
1892 | \centering
|
---|
1893 | \includegraphics{plot-string-allocn.pdf}
|
---|
1894 | \begin{tabularx}{\linewidth}{>{\centering\arraybackslash}X >{\centering\arraybackslash}X} (a) Vertical, Lower is better. \\ Horizontal, leftward is better. & (b) \hspace*{5pt} STL CFA \hspace*{20pt} STL \hspace*{10pt} CFA \hspace*{10pt} \end{tabularx}
|
---|
1895 | \caption{Space and time performance, under varying fraction-live targets, for the five string lengths shown, at \emph{Varying 16 and up} corpus construction.}
|
---|
1896 | \label{fig:string-graph-allocn}
|
---|
1897 | \end{figure}
|
---|
1898 |
|
---|
1899 | \VRef[Figure]{fig:string-graph-allocn} shows the experimental results.
|
---|
1900 | In plot (a), there is one labeled curve for each of the five chosen string sizes, 20, 50, 100, 200, 500.
|
---|
1901 | A labeled curve shows the \CFA speed and space combinations achievable by varying the fraction-live tuning parameter.
|
---|
1902 | Stepping along the curve from top-left toward bottom-right means the string library has a smaller fraction of its heap remain live after collection, \ie it doubles its size more often.
|
---|
1903 | Hence, memory approximately doubles between points.
|
---|
1904 | The additional memory means less time is spent collecting, so the curve shows lower (better) times per operation (y-axis).
|
---|
1905 | This doubling benefit diminishes, so the curves begin to flatten.
|
---|
1906 |
|
---|
1907 | The point chosen as \CFA's default liveness threshold (20\%) is marked with a circle.
|
---|
1908 | For most string lengths, this point occurs as the doubling benefit becomes subjectively negligible.
|
---|
1909 | At len-500, the amount of space needed to achieve 20\% liveness is so much that last-level cache misses begin occurring generating a further slowdown.
|
---|
1910 | This effect is an anomaly of the experimental setup trying to compare such varied sizes in one view;
|
---|
1911 | the len-500 default point is included only to provide a holistic picture of the STL comparisons (discussed next).
|
---|
1912 |
|
---|
1913 | Staying within plot (a), each \emph{tradeoff} line (green) connects the default-tuned \CFA performance point with its length-equivalent STL performance point.
|
---|
1914 | STL always uses less memory (occurs to the left of) than its \CFA equivalent.
|
---|
1915 | Ideally, \CFA results would be faster (STL occurs above it);
|
---|
1916 | however, this inversion only occurs for smaller string lengths.
|
---|
1917 | That is, the STL-to-\CFA tradeoff line goes down and to the right for small strings, but for longer strings, it goes up and to the right.
|
---|
1918 |
|
---|
1919 | Plot (b) offers insight into why larger lengths are not currently showing the anticipated tradeoff, and suggests possible remedies.
|
---|
1920 | This plot breaks down the time spent, comparing STL--\CFA tradeoffs, at successful len-50 with unsuccessful len-200.
|
---|
1921 | Data are sourced from running the experiment under \emph{perf}, recording samples of the call stack, and imposing a mutually-exclusive classification on these call stacks.
|
---|
1922 | Reading a stacked bar from the top down, \emph{text import} captures samples where a routine like @memcpy@ is running, so that the string library is copying characters from the corpus source into its allocated working space.
|
---|
1923 | \emph{Malloc-free} means literally one of those routines (taking nontrivial time only for STL), while \emph{gc} is the direct \CFA(-only) equivalent.
|
---|
1924 | All of the attributions so far occur while a string is live; further time spent in a string's lifecycle management functions is attributed \emph{ctor-dtor}.
|
---|
1925 | Skipping to the bottom-most attribution, \emph{harness-leaf} represents samples where the youngest live stack frame is simply the recursive @helper@ routine of \VRef[Figure]{fig:string-perf-alloc}.
|
---|
1926 | The skipped attribution \emph{Other} has samples that meet none of the criteria above.
|
---|
1927 |
|
---|
1928 | \PAB{From Mike: need to add the sep-comp side bar to the graph.}
|
---|
1929 |
|
---|
1930 | Beside \CFA's principal bars, a bar for separate-compilation overhead (\emph{sep.\ comp.}) shows the benefit that STL enjoys by using monolithic compilation.
|
---|
1931 | \CFA currently forgoes this benefit.
|
---|
1932 | This overhead figure was obtained by hacking a version of the \CFA string library to have a header-only implementation and measuring the resulting speed.
|
---|
1933 | The difference between separately compiled (normal) and header-only (hacked) versions is the reported overhead.
|
---|
1934 | It represents how much \CFA could speed up if it switched to a header-only implementation to match STL.
|
---|
1935 | The difference jumps noticeably between the different string sizes, but has little correlation with string size ($r=0.3$).
|
---|
1936 | Associating this potential improvement with the \emph{other} attribution is a stylistic choice.
|
---|
1937 |
|
---|
1938 | Analyzing the stacked bars from the bottom up, the first two categories, \emph{harness-leaf} and \emph{other} both give baseline times that should not be matters of STL-\CFA difference.
|
---|
1939 | The \emph{harness-leaf} category is called out as a quality check; this attribution is equal across all four setups, ruling out mysterious ``everything is X\% slower'' effects.
|
---|
1940 | But with the \emph{other} attribution, STL beats \CFA by an amount that matches the STL's benefit from avoiding separate compilation.
|
---|
1941 | In the \emph{ctor-dtor} category, \CFA is spending more time than STL to inter-link its string handles.
|
---|
1942 | Comparing STL's \emph{malloc-free} with \CFA's \emph{gc}, \CFA's is considerably shorter, in spite of its copying, because \emph{gc} only spends time on live strings, while \emph{malloc-free} works on all strings.
|
---|
1943 | Most of the every-string bookkeeping occurs under STL's \emph{malloc-free} and \CFA's \emph{ctor-dtor}.
|
---|
1944 | So the critical comparison is STL's $(\textit{ctor-dtor} + \textit{malloc-free})$ \vs \CFA's $(\textit{ctor-dtor} + \textit{gc})$.
|
---|
1945 | Here, \CFA is a clear winner.
|
---|
1946 | Moreover, the discussion so far holds for both the successful and unsuccessful string lengths, albeit with the length-correlated duration of \emph{gc} (due to copying) encroaching on \CFA's advantage, though not eliminating it.
|
---|
1947 | The total attributions so far see \CFA ahead, possibly by more than is shown, depending on how one views the separate-compilation difference.
|
---|
1948 | Under a \CFA-generous separate-compilation stance, \CFA is equal or ahead in every important category so far.
|
---|
1949 |
|
---|
1950 | The remaining attribution, \emph{text-import}, is thus a major reason that \CFA is currently unsuccessful at delivering improved speed with long strings. \PAB{From Mike: need to finish this point.}
|
---|
1951 |
|
---|
1952 | % \subsection{Test: Normalize}
|
---|
1953 |
|
---|
1954 | % This test is more applied than the earlier ones.
|
---|
1955 | % It combines the effects of several operations.
|
---|
1956 | % It also demonstrates a case of the \CFA API allowing user code to perform well, while being written without overt memory management, while achieving similar performance in STL requires adding memory-management complexity.
|
---|
1957 |
|
---|
1958 | % To motivate: edits being rare
|
---|
1959 |
|
---|
1960 | % The program is doing a specialized find-replace operation on a large body of text.
|
---|
1961 | % In the program under test, the replacement is just to erase a magic character.
|
---|
1962 | % But in the larger software problem represented, the rewrite logic belongs to a module that was originally intended to operate on simple, modest-length strings.
|
---|
1963 | % The challenge is to apply this packaged function across chunks taken from the large body.
|
---|
1964 | % Using the \CFA string library, the most natural way to write the helper module's function also works well in the adapted context.
|
---|
1965 | % Using the STL string, the most natural ways to write the helper module's function, given its requirements in isolation, slow down when it is driven in the adapted context.
|
---|
1966 |
|
---|
1967 | \begin{lstlisting}
|
---|
1968 | void processItem( string & item ) {
|
---|
1969 | // find issues in item and fix them
|
---|
1970 | }
|
---|
1971 | \end{lstlisting}
|
---|