-2

my code below which using each() actually can work nicely, but is it use for to loop is better than to use each() ? use for to loop will reduce the timeload compare with each(); ? because in future i still will add more for the data type.. means not only c1,c2,still will have more type is coming,

my html ,

<div class ="box red" data-type="c1" data-title="c1 content" id="cp-1">
  <div class= "title">c1 content</div>
</div>
<div class ="box green" data-type="c1" data-title="c2 content" id="cp-2">
  <div class= "title">c2 content</div>
</div>

javascript :

 $(document).ready(function() {
        var cp = $('.box');
        //  Unique Id for each
        var idCp = 0;
        for (var i = 0; i < cp.length; i++) 
        {
            idCp++;
            cp[i].id = "cp-" + idCp;
        }

           cp.each(function() {
                var cp = $(this);
                var cpTitle = cp.attr("data-title") + "";

                // different Data type
                if (cp.data('type') == "c1") 
                {
                    cp.addClass('red').css(
                        {
                            "background-color" : "red",
                            "padding": "20px", 
                            "display": "table"}
                        );
                    cp.append('<div class="title">' + cpTitle + '</div>');
                } 

                else if (cp.data('type') == "c2") 
                {
                    cp.addClass('green').css(
                        {
                            "background-color" : "green", 
                            "padding": "20px", 
                            "display": "table"}
                        );
                    cp.append('<div class="title">'+ cpTitle + '</div>');
                } else {
                    return false;
                }
            });
        });

2 Answers2

3

Generally, native language constructs are faster than library functions. So, performance-wise, you are better off using a for loop, but unless you have several thousands of elements to iterate, the difference between the two will be barely noticeable.

In my opinion, your code is particularly ineffective, anyway, irrespective of whether you're using each or a for loop. Here's how I would write it using just one for loop, instead of a for loop and an each function call as you do:

Snippet:

/* ----- JavaScript ----- */
$(document).ready(function() {
  var
    /* Cache the boxes and create a data object mapping the types to their classes. */
    cp = $(".box"),
    types = {
      c1: "red",
      c2: "green"
    };
    
  /* Iterate over every box. */
  for (var i = 0; i < cp.length; i++) {
    var
      /* Cache the current box and its type. */
      box = $(cp[i]),
      type = box.data("type");
      
    /* Give the box a unique incremental id. */
    cp[i].id = "cp-" + (i + 1);
    
    /* Check whether the type exists in the types object. */
    if (type in types) {    
      /* Add the correct class to the box based on its data type. */
      box.addClass(types[type]);
      
      /* Create a title for the box. */
      box.append("<div class='title'>" + box.data("title") + "</div>");
    }
    else return false;
  }
});
/* ----- CSS ----- */
.box {
  display: table;
  padding: 20px;
}

.red {background-color: red}
.green {background-color: green}
<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class ="box red" data-type="c1" data-title="c1 content" id="cp-1"></div>
<div class ="box green" data-type="c1" data-title="c2 content" id="cp-2"></div>

Note:

When writing code, you should aim to achieve a balance between code performance and code readability, because a slow code can tweaked to be made faster but an illegible code is very hard to maintain.

Here is great answer outlining the ideal approach (in my opinion) when it comes to the readability vs performance dilemma. I have also added a couple of good answers that aim to compare the use of each and the for loop:

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
0

You can check for explanation and performance comparison below.

Speed Question jQuery.each vs. for loop

I checked different tests too. What should you know is that, generally, native functions runs much faster because libraries are already using them and do more complex things. But in some test cases $.each() can be faster than for loop.

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
Yusuf Kandemir
  • 810
  • 7
  • 16
  • 1
    _"in some test cases `$.each()` can be faster than `for` loop."_ : What cases? Why don't you include an example, so that the OP can benefit more from your answer? – Angel Politis Jan 28 '18 at 09:53
  • @AngelPolitis they are not fully specific, I saw one [here](https://jsperf.com/jquery-each-vs-for-loop/) but it can give different results at different times. It said each is faster than for like 1-2 times. Its about client's performance at that moment. Your answer and pointed answers are enough already so anyone read my answer can only benefit from that link. It contains nice info. You asked like scolding me but thanks for advice anyways. I am 5 days old in answering questions. – Yusuf Kandemir Jan 28 '18 at 10:38
  • I had no such intent. What I aimed at was to give you an extra push to improve your answer. That's all – Angel Politis Jan 29 '18 at 01:16