From d195111a9dae7376288fe39b60899736425a3ca7 Mon Sep 17 00:00:00 2001 From: Tobie Langel Date: Sat, 13 Oct 2007 19:05:19 +0000 Subject: [PATCH] Performance improvements to String#times. --- CHANGELOG | 2 ++ src/string.js | 4 +--- test/unit/string.html | 17 +++++++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) 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) {