performance javascript code Vs php


I have done tests with two codes that do the same, load a defined selection with the options of a request that is made bd. php code:

<div id="Contenedor" style="position:absolute; height: 0px; width: 0px; opacity: 0;">
 <select class="ui-keyboard-input ui-widget-content ui-corner-all ui-keyboard-input-current" size='9'; style="text-align: left; width: 250px; height: 180px" id="Select" disabled="disabled" aria-haspopup="true" role="textbox" type="text">

 $query= "SELECT 'id','name' FROM 'lista'";
    while ($fila = mysql_fetch_assoc($data)) {
        $code= $fila['id'];
        $name= $fila['name'];
        $conc= $id.": ".$name; 
        <option value="<?php echo $code;?>"><?php echo $conc;?></option>

Javascript code for the same select:

  var sele=(JSON.parse(data));
  for(x=0; x<sele.length;x++){
   $("#Select").append(new Option(x+': '+sele[x],x));  


I put the complete code but what it consumes time in each one of the routines is the filling loop of the options, the While in case of php and the for in case of javascript. Performing different tests it turns out that the javascript code takes a minute to load 4000 records while php takes about 800 milliseconds, how is such a difference possible? Is there anything that can be improved in javascript? My question is justified by topic that doing it through javascript, the select is loaded and I do not have to reload every time I enter the section, while by php, every time the section is loaded I'm making a call to bd.

asked by Quarkbite 25.10.2017 в 11:39

1 answer


There is a big difference between one code and another. In php in the loop you are simply modifying a string, whereas in javascript what you are doing is adding options to an element that is in the DOM of the page that the browser is showing. Access to the DOM always implies low performance.

A simple optimization you could do in your javascript code is to not add the options to a select already added in the DOM, if not add them to a select in memory and then add this element select to DOM.

Look at this example with the two options:

var data=[];
for (var i=0 ; i<4000; data.push('Opción ' + ++i));

  var cont = new Date();
  for(x=0; x<data.length;x++){
   $("#Select").append(new Option(x + ': ' + data[x], x));
  console.log('Opción 1: ' + (new Date() - cont)); 
  cont = new Date();
  var $select2 = $('<select></select>');
  for(x=0; x<data.length;x++){
   $select2.append(new Option(x + ': ' + data[x], x));
  console.log('Opción 2: ' + (new Date() - cont)); 
<script src=""></script>
<select id="Select"></select>
answered by 25.10.2017 / 11:58