translate vs position left/top vs css margin left/top (v58)

Revision 58 of this benchmark created by vamp on


Description

I have added the 3d variants to the code snippets, as well as forcing the browser to actually update the styles, reading the ".offsetTop" property.

The problem with this jsperf is that it really only tests the JavaScript side of things, and only at the point of execution. Things like translate3d would perform better over a longer period of time, as the task is off-loaded onto the GPU in most cases. Unfortunately, this performance cannot be properly measured by jsperf.

Preparation HTML

<div id="elem" style="position: relative; background:#ccc; width:10px; height:10px;">
</div>
<script>
  var elem = document.getElementById("elem");
  var style = elem.style;
  var template = document.getElementById("elem").cloneNode();
  var transform = (function() {
    if (undefined !== style.WebkitTransform) {
      return "WebkitTransform";
    } else if (undefined !== style.MozTransform) {
      return "MozTransform";
    } else if (undefined !== style.OTransform) {
      return "OTransform";
    } else if (undefined !== style.msTransform) {
      return "msTransform";
    } else if (undefined !== style.WebkitTransform) {
      return "WebkitTransform";
    } else {
      return "transform";
    }
  })();
</script>

Setup

var newElem = template.cloneNode();
    elem.parentNode.replaceChild(newElem, elem);
    
    elem = newElem;
    var style = newElem.style;
    var x = Math.random() * 10;

Test runner

Ready to run.

Testing in
TestOps/sec
translate
style[transform] = "translate(" + x + "px, " + x + "px)";

// forces styles to be pushed through
!!elem.offsetTop;
ready
translate X/Y
style[transform] = "translateX(" + x + "px) translateY(" + x + "px)";

// forces styles to be pushed through
!!elem.offsetTop;
ready
translateX/Y/Z
style[transform] = "translateX(" + x + "px) translateY(" + x + "px) translateZ(0)";

// forces styles to be pushed through
!!elem.offsetTop;
ready
translate, translateZ
style[transform] = "translate(" + x + "px, " + x + "px) translateZ(0)";

// forces styles to be pushed through
!!elem.offsetTop;
ready
translate3d
style[transform] = "translate3d(" + x + "px, " + x + "px, 0)";

// forces styles to be pushed through
!!elem.offsetTop;
ready
position left/top
x += "px";
style.left = x;
style.top = x;

// forces styles to be pushed through
!!elem.offsetTop;
ready
margin left/top
x += "px";
style.marginLeft = x;
style.marginTop = x;

// forces styles to be pushed through
!!elem.offsetTop;
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.