0

I have a table which contains many rows. I need to find the td data using jquery. There are many ways to get that data

1. $("table tr td").each(function(){})

2. $("table").find("tr").find("td").each(function(){})

Now I want to know which method in better and why?

Vishu238
  • 673
  • 4
  • 17

1 Answers1

5

Do profiling using console.time and console.timeEnd will give you ther performance in microseconds .

console.time('withSelector');
   for(var i=0; i<10E4 ;i++)
      $("table tr td");
console.timeEnd('withSelector');

the same for $("table").find("tr").find("td") .. Run snippet below

Result

enter image description here

Analysis :

With selector is better than find

function withSelector() {
   $("table tr td");
}



function withFind() {
   $("table").find("tr").find("td")
}

function run(fn, times) { 
   console.time(fn.name);
   for(var i=0; i<times ;i++)
      fn();
   console.timeEnd(fn.name);
}

run(withSelector, 10E4);

run(withFind, 10E4);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
   
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>
Community
  • 1
  • 1
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254