diff --git a/CHANGELOG b/CHANGELOG index 7b872f8..c9cd57b 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Performance improvements to String#times. [Martin Ström] + * Make Ajax.Response#getHeaderJSON and Ajax.Response#getResponseJSON pseudo private instance methods. [Tobie Langel] * Make ObjectRange use the new Class.create syntax. [Mislav Marohnić] diff --git a/src/string.js b/src/string.js index 11f09ca..0a994e2 100644 --- a/src/string.js +++ b/src/string.js @@ -119,9 +119,7 @@ Object.extend(String.prototype, { }, times: function(count) { - var result = ''; - for (var i = 0; i < count; i++) result += this; - return result; + return count < 1 ? '' : new Array(count + 1).join(this); }, camelize: function() { diff --git a/test/unit/string.html b/test/unit/string.html index 52ff8e1..9241e52 100644 --- a/test/unit/string.html +++ b/test/unit/string.html @@ -463,13 +463,30 @@ }}, testTimes: function() {with(this) { + assertEqual('', ''.times(0)); assertEqual('', ''.times(5)); + assertEqual('', 'a'.times(-1)); assertEqual('', 'a'.times(0)); assertEqual('a', 'a'.times(1)); + assertEqual('aa', 'a'.times(2)); assertEqual('aaaaa', 'a'.times(5)); assertEqual('foofoofoofoofoo', 'foo'.times(5)); assertEqual('', 'foo'.times(-5)); + + /*window.String.prototype.oldTimes = function(count) { + var result = ''; + for (var i = 0; i < count; i++) result += this; + return result; + }; + + benchmark(function() { + 'foo'.times(15); + }, 1000, 'new: '); + + benchmark(function() { + 'foo'.oldTimes(15); + }, 1000, 'previous: ');*/ }}, testToJSON: function() {with(this) {