Select2 performance for large set of items

select2 options
rails select2
select2 ajax
select2 container
dropdown with large data
select2 not showing options
select2 example
select2 widget

I'm using select2 jquery plugin with twitter bootstrap. It's working fine for smaller number of items. But when the list is huge (more than 1500 items) it really slows down. It's slowest in IE.

Normal Dropdownlist works very fast with more than 1500 items. Are there any workarounds for this situation?

You can make this work good even in IE8 with paginating the suggestions,

Code:

// Function to shuffle the demo data
function shuffle(str) {
  return str
    .split('')
    .sort(function() {
      return 0.5 - Math.random();
  })
.join('');
}

// For demonstration purposes we first make
// a huge array of demo data (20 000 items)
// HEADS UP; for the _.map function i use underscore (actually lo-dash) here
function mockData() {
  return _.map(_.range(1, 20000), function(i) {
    return {
      id: i,
      text: shuffle('te ststr ing to shuffle') + ' ' + i,
    };
  });
}
(function() {
  // init select 2
  $('#test').select2({
    data: mockData(),
    placeholder: 'search',
    multiple: true,
    // query with pagination
    query: function(q) {
      var pageSize,
        results,
        that = this;
      pageSize = 20; // or whatever pagesize
      results = [];
      if (q.term && q.term !== '') {
        // HEADS UP; for the _.filter function i use underscore (actually lo-dash) here
        results = _.filter(that.data, function(e) {
          return e.text.toUpperCase().indexOf(q.term.toUpperCase()) >= 0;
        });
      } else if (q.term === '') {
        results = that.data;
      }
      q.callback({
        results: results.slice((q.page - 1) * pageSize, q.page * pageSize),
        more: results.length >= q.page * pageSize,
      });
    },
  });
})();

working example with 20000 items here: http://embed.plnkr.co/db8SXs/preview

plnkr embed does not support IE8 so try it out on IE8 with this link instead: http://run.plnkr.co/plunks/db8SXs/

Handle Large Data in Select2 Dropdown, In the <select> element, select2 library binds all options in one go and this <p>​To improved performance of the dropdown with large data sets  I’m using select2 jquery plugin with twitter bootstrap. It’s working fine for smaller number of items. But when the list is huge (more than 1500 items) it really slows down. It’s slowest in IE. Normal Dropdownlist works very fast with more than 1500 items. Are there any workarounds for this situation?

I know it's an old question, but I wanted to share what worked for me. If you must pre-load the big list(depending on if you're starting from scratch or building on someone else's code, this may be easier), use the minimumInputLength as described here in the documentation. The huge list of options doesn't show until the user has typed a couple of characters. This greatly reduces the performance hit while rendering them when the Select2 dropdown is actually selected. Hope that helps!

Select2 slow performance for large list, My list is built in a Select Distinct SQL statement that returns a single column during the preparation, and contains over 30000 items. In the <select> element, select2 library binds all options in one go and this is causing the slowness for the large data. So instead of using the <select> element, you can use the textbox dropdown and select2 library helps to bind the textbox as the dropdown menu so it will give the fill of the dropdown menu to the users.

So keep in mind you are loading >1500 actual elements onto the page in the form of <option>s, which can end up hurting page performance as well. As a user suggested in the a comment, you can solve the performance issue by making an AJAX call to a backend service that will return your values.

Select2 Ajax how-to

Handle a large data set? - How Do I, However, I have a large list of data that select2 bogs down on. $(function () { items = [] for (var i = 0; i < 1000; i++) { items.push({ id: i, text  My list is built in a Select Distinct SQL statement that returns a single column during the preparation, and contains over 30000 items. The column returned from the SQL statement is used for both the Source Attribute and Source Identifier. Is there a way to make the Select2 widget (or another searchable dropdown) respond faster? Thank you.

Here's a working version for Select2 v4

Based on the answer here: and modified it to make searching work with lo-dash

$(function () {
    items = []
    for (var i = 0; i < 1000; i++) {
        items.push({ id: i, text : "item " + i})
    }

    pageSize = 50

    jQuery.fn.select2.amd.require(["select2/data/array", "select2/utils"],

    function (ArrayData, Utils) {
        function CustomData($element, options) {
            CustomData.__super__.constructor.call(this, $element, options);
        }
        Utils.Extend(CustomData, ArrayData);

        CustomData.prototype.query = function (params, callback) {

            var results = [];
            if (params.term && params.term !== '') {
              results = _.filter(items, function(e) {
                return e.text.toUpperCase().indexOf(params.term.toUpperCase()) >= 0;
              });
            } else {
              results = items;
            }

            if (!("page" in params)) {
                params.page = 1;
            }
            var data = {};
            data.results = results.slice((params.page - 1) * pageSize, params.page * pageSize);
            data.pagination = {};
            data.pagination.more = params.page * pageSize < results.length;
            callback(data);
        };

        $(document).ready(function () {
            $("select").select2({
                ajax: {},
                dataAdapter: CustomData
            });
        });
    })
});

JsFiddle: http://jsfiddle.net/nea053tw/

Edit: Fiddle changed.

Select2 performance for large set of items, I'm using select2 jquery plugin with twitter bootstrap. It's working fine for smaller number of items. But when the list is huge (more than 1500  Select2 Huge DataSet Poor Performance. GitHub Gist: instantly share code, notes, and snippets.

This is very old question and answer and even we have newer version of select2. but if someone is trying to search in optgroup too. can try this solution.

http://jsfiddle.net/na1zLkz3/4/

    // Function to shuffle the demo data 
var shuffle = function (str) {
    return str.split('').sort(function () {
      return 0.5 - Math.random();
    }).join('');
  };

// For demonstration purposes we first make
// a huge array of demo data (20 000 items)
// HEADS UP; for the _.map function i use underscore (actually lo-dash) here
var mockData = function () {
    var array = _.map(_.range(1, 10), function (i) {
        return {
          id  : i,
          text: shuffle('te ststr ing to shuffle') + ' ' + i
        };
      });
    return array;
  };
  var mockData1 = function () {
    var array = _.map(_.range(10, 15), function (i) {
        return {
          id  : i,
          text: shuffle('te ststr ing to shuffle') + ' ' + i
        };
      });
    return array;
  };
  var mockData2 = function () {
    var array = _.map(_.range(15, 20), function (i) {
        return {
          id  : i,
          text: shuffle('te ststr ing to shuffle') + ' ' + i
        };
      });
    return array;
  };
  // create demo data
  var dummyData = mockData();
  var dummyData1 = mockData1();
  var dummyData2 = mockData2();
  dummyData.push({
  text: 'canada',
  children: dummyData1
  });
  dummyData.push({
  text: 'USA',
  children: dummyData2
  });

  // init select 2
  $('#ddlCar').select2({
    data             : dummyData,
    // init selected from elements value
    initSelection    : function (element, callback) {
      var initialData = [];
      $(element.val().split(",")).each(function () {
        initialData.push({
          id  : this,
          text: this
        });
      });
      callback(initialData);
    },

    // NOT NEEDED: These are just css for the demo data
    dropdownCssClass : 'capitalize',
    containerCssClass: 'capitalize',

    // NOT NEEDED: text for loading more results
    formatLoadMore   : function() {return 'Loading more...'},

    // query with pagination
    query            : function (q) {
      var pageSize,
        results;
      pageSize = 20; // or whatever pagesize
      var results  = [];
      if (q.term && q.term !== "") {
        // HEADS UP; for the _.filter function i use underscore (actually lo-dash) here
        var results = this.data;
        var results = _.filter(results, function (e) {
            if(typeof e.children != 'undefined')
          {
            subresults = _.filter(e.children, function (f) {
                return (f.text.toUpperCase().indexOf(q.term.toUpperCase()) >= 0);
            });
            if(subresults.length > 0)
                return true;
            return false;
          }
          return (e.text.toUpperCase().indexOf(q.term.toUpperCase()) >= 0);
        });
        newresults = [];
        for (var i = 0, len = results.length; i < len; i++) {
        newresults[i] = {};
        if(typeof results[i].text != 'undefined')
            newresults[i].text = results[i].text;
        if(typeof results[i].id != 'undefined')
            newresults[i].id = results[i].id;
        if(typeof results[i].children != 'undefined')
        {
            newresults[i].children = results[i].children;
            newresults[i].children = _.filter(newresults[i].children, function (f)                          {
                return (f.text.toUpperCase().indexOf(q.term.toUpperCase()) >= 0);
            });
        }
      }
      results = newresults;
      } else if (q.term === "") {
        results = this.data;

      }

      q.callback({
        results: results.slice((q.page - 1) * pageSize, q.page * pageSize),
        more   : results.length >= q.page * pageSize
      });
    }
  });

select2 with pagination for large data sets, href="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.min.css" /> <link <​p>for improved performance with large data sets (20 000 items)</p> </div>  After a looking I saw that select2 renders the html for each select option and appends it to the select inside a for loop. Instead I believe it should store the html for each option in a var and append it to the select once the loop has finished (rather than inside the loop). I believe that change will fix any performance issues with large lists.

select2 performance for large lists, select2 performance for large lists Hi, this is a very cool piece of sw,but had some performance questions. I have a list of around 10,500 You received this message because you are subscribed to the Google Groups "select2" group. For more options, visit https://groups.google.com/groups/opt_out. > >. This includes placeholders and pre-existing selections that are displayed, so you must ensure that your templating functions can support them. Limiting the number of selections Select2 multi-value select boxes can set restrictions regarding the maximum number of options that can be selected.

Slow load on large dataset… · Issue #713 · select2/select2 · GitHub, For a large data sets, I think it's better not to load all data on page load. I disagree that 20,000 items is inherently enough to do paging on. To programmatically select an option/item for a Select2 control, use the jQuery .val() method: $('#mySelect2').val('1'); // Select the option with a value of '1' $('#mySelect2').trigger('change'); // Notify any JS components that the value changed. You can also pass an array to val make multiple selections:

jQuery and JavaScript Performance, For the rewrite of Select2, we decided that fixing the performance need to set the data on a large amount of objects, and you don't care about  Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options. In your language Select2 comes with support for RTL environments , searching with diacritics and over 40 languages built-in.

Comments
  • Use AJAX :) instead of loading the whole data
  • As an aside: I feel this is formatted as some poem. And please use the Shift key?
  • This is a great solution. had an issue where having the possibility of 200 dropdowns on screen at once and having over x items in the dropdowns was causing lonnnnnnggg page loads. This was able to bring it down to a couple seconds instead of 2 minutes.
  • Thanks for sharing your code. If you're still around, how can I have default value(s) selected? Unfortunately, unlike before, running $('#e24').select2('val', ["150"]); after your instantiation code does not work.
  • It is possible if you set the value before initializing the select2 as e.g. $('#e24').val([firstSelectedValue, secondSelectedValue) and add initSelection : function (element, callback) { var data = []; $(element.val().split(",")).each(function () { data.push({id: this, text: this}); }); callback(data); }, inside the select2 init according to select2 docs. I could not get it to work with e.g. val : ["1", "2"] inside the initializer though. Updated working plnkr: http://embed.plnkr.co/db8SXs/preview
  • See my answer for update of this code, it searches even in the optgroup
  • plnkr examples now updated and are working, note: only in Select2 v3
  • Only downside is some of my users like to scroll down the list and then select a few items that are next to each other. You can allow this by setting closeOnSelect:false. If you use minimumInputLength, the user can't select multiple items at a time, just one at a time.
  • Wanted to add that the page loading can still be slow if the page has many dropdowns with large lists
  • I've called my data using ajax. Data is showing good but the problem is I can't select any option.
  • The hero we need🎉