Repeat a string: Difference between revisions

Content added Content deleted
(→‎{{header|OCaml}}: Bytes instead of String)
Line 1,487: Line 1,487:
// Slower version
// Slower version
func repeatString(n: Int) -> String {
func repeatString(n: Int) -> String {
return "".join(Array(count: n, repeatedValue: self))
return Array(count: n, repeatedValue: self).joinWithSeparator("")
}
}

// Faster version
// Faster version
// benchmarked with a 1000 characters and 100 repeats the fast version is approx 500 000 times faster :-)
// benchmarked with a 1000 characters and 100 repeats the fast version is approx 500 000 times faster :-)
func repeat(n:Int) -> String {
func repeatString2(n:Int) -> String {
var result = self
var result = self
for _ in 1 ..< n {
for _ in 1 ..< n {
result.extend(self) // Note that String.extend is up to 10 times faster than "result += self"
result.appendContentsOf(self) // Note that String.extend is up to 10 times faster than "result += self"
}
}
return result
return result
Line 1,501: Line 1,501:
}
}


println( "ha".repeatString(5) )
print( "ha".repeatString(5) )
println( "he".repeat(5) )</lang>
print( "he".repeatString2(5) )</lang>
{{out}}
<pre>
<pre>
hahahahaha
hahahahaha