Technique 2: Avoid references to objects or object properties
Original code for creating strings
Be aware that there's one innocent reference to an object property
The use of this object property destroys the generality of the computer program. The program assumes that x must be a string of length one. This limits the application of the
stringFill1() function to anything except repetition of single characters. Even single characters cannot be used if they contain multiple bytes like the HTML entity
The worst problem caused by this unnecessary use of an object property
is that the function creates an infinite loop if tested on an empty input string
x. To check generality, apply a program to the smallest possible amount of input. A program which crashes when asked to exceed the amount of available memory has an excuse. A program like this one which crashes when asked to produce nothing is unacceptable. Sometimes pretty code is poisonous code.
Simplicity may be an ambiguous goal of computer programming, but generally it's not. When a program lacks any reasonable level of generality, it's not valid to say, "The program is good enough as far as it goes." As you can see, using the string.length property prevents this program from working in a general setting, and in fact, the incorrect program is ready to cause a browser or system crash.
Of course. Just use integers.
Optimized code for creating strings
Timing code to compare
The success so far of
stringFill1() takes 47.297 microseconds (millionths of a second) to fill a 100-byte string,
stringFill2() takes 27.68 microseconds to do the same thing. That's almost a doubling in
performance by avoiding a reference to an object property.