Repeat a string: Difference between revisions

Line 1,518:
The following version is an enhanced version of the [http://rosettacode.org/mw/index.php?title=Repeat_a_string#Recursive_version recursive ActionScript], where we're using bit operation along with iterative doubling of the string to get to the correctly repeated version of the text in the most effective manner without recursion. When benchmarked against the plain iterative version in previous section, this version is marginally better, but only my a very small percentage. The critical factor for making the repeat function effective when using larger strings (1000 characters) and multiple repeats (1000 repeats :-) ) was to to exchange the '+=' with 'String.extend' method.
 
<lang swift>extension String {
func repeatBiterative(count: Int) -> String {
var reduceCount = count
var result : String = "";
var doubled = self
while (reduceCount != 0) {
if (reduceCount & 1 == 1) {
result.extendappendContentsOf(doubled)
}
reduceCount >>= 1
if (reduceCount != 0) {
doubled.extendappendContentsOf(doubled)
}
}
Line 1,537:
 
"He".repeatBiterative(5)</lang>
{{out}}
<pre>
"HeHeHeHeHe"
Anonymous user