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 |
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 |
func repeatString2(n:Int) -> String { |
||
var result = self |
var result = self |
||
for _ in 1 ..< n { |
for _ in 1 ..< n { |
||
result. |
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: | ||
} |
} |
||
print( "ha".repeatString(5) ) |
|||
print( "he".repeatString2(5) )</lang> |
|||
{{out}} |
|||
<pre> |
<pre> |
||
hahahahaha |
hahahahaha |