fastest way to check if a container has any content
JavaScript performance comparison
Info
Most use $(element).children().length > 0 but I wonder if there's a much faster way if you just have to check for any content to be present.
Preparation code
<ul id="container">
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
</ul>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
var container = document.getElementById('container'),
$container = $(container);
};
</script>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Common jQuery way |
|
pending… |
pure JS way |
|
pending… |
jQuery check for first only |
|
pending… |
js check for first only |
|
pending… |
jQuery check content string |
|
pending… |
js check content string |
|
pending… |
Check if is parent |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments