From dea8ad4c49ce2de928b7c38e8c01b6a4001be095 Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Sat, 13 Oct 2012 23:29:51 -0700 Subject: [PATCH] Optimize `_.contains` and `_.omit`. Former-commit-id: f1d7b5699bae6de90d880fe593531f7d3772924e --- lodash.js | 15 +++++++++++---- perf/perf.js | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/lodash.js b/lodash.js index 5599583d5..383600f81 100644 --- a/lodash.js +++ b/lodash.js @@ -1743,7 +1743,7 @@ forIn(object, function(value, key, object) { if (isFunc ? !callback(value, key, object) - : indexOf(props, key) < 0 + : indexOf(props, key, 1) < 0 ) { result[key] = value; } @@ -1868,9 +1868,16 @@ * // => true */ function contains(collection, target) { - return toString.call(collection) == stringClass - ? collection.indexOf(target) > -1 - : some(collection, function(value) { return value === target; }); + var length = collection ? collection.length : 0; + if (length === +length) { + return (toString.call(collection) == stringClass + ? collection.indexOf(target) + : indexOf(collection, target) + ) > -1; + } + return some(collection, function(value) { + return value === target; + }); } /** diff --git a/perf/perf.js b/perf/perf.js index bf8212b7a..ae3ff2c41 100644 --- a/perf/perf.js +++ b/perf/perf.js @@ -512,6 +512,28 @@ /*--------------------------------------------------------------------------*/ + suites.push( + Benchmark.Suite('`_.contains` iterating an array') + .add('Lo-Dash', '\ + lodash.contains(numbers, 19)' + ) + .add('Underscore', '\ + _.contains(numbers, 19)' + ) + ); + + suites.push( + Benchmark.Suite('`_.contains` iterating an object') + .add('Lo-Dash', '\ + lodash.contains(object, 19)' + ) + .add('Underscore', '\ + _.contains(object, 19)' + ) + ); + + /*--------------------------------------------------------------------------*/ + suites.push( Benchmark.Suite('`_.countBy` with `callback` iterating an array') .add('Lo-Dash', '\