The Truth About Traditional JavaScript Benchmarks (Part 2 - SunSpider)

Continuing on with the series, in the post, allow me to run you through the first example of how JS engines can and do game benchmarks by showing you a few examples from SunSpider.

· Performance Zone · Analysis

picking up where we left off with the previous post , my goal with the rest of this series is to highlight a few concrete examples that illustrate why i think it’s not only useful but crucial for the health of the javascript community to stop paying attention to static peak performance benchmarks above a certain threshold.

so, in the post, allow me to run you through the first example of how js engines can and do game benchmarks.

the notorious sunspider examples

a blog post on traditional javascript benchmarks wouldn’t be complete without pointing out the obvious sunspider problems. so, let’s start with the prime example of a performance test that has limited applicability in the real world: the bitops-bitwise-and.js performance test.


there are a couple of algorithms that need fast bitwise and, especially in the area of code transpiled from c/c++ to javascript, so it does indeed make some sense to be able to perform this operation quickly. however, real-world web pages will probably not care whether an engine can execute bitwise and in a loop 2x faster than another engine. but staring at this code for another couple of seconds, you’ll probably notice that bitwiseandvalue will be 0 after the first loop iteration and will remain 0 for the next 599999 iterations. so once you get this to good performance, i.e. anything below 5ms on decent hardware, you can start gaming this benchmark by trying to recognize that only the first iteration of the loop is necessary, while the remaining iterations are a waste of time (i.e. dead code after loop peeling ). this needs some machinery in javascript to perform this transformation, i.e. you need to check that bitwiseandvalue is either a regular property of the global object or not present before you execute the script, there must be no interceptor on the global object or it’s prototypes, etc., but if you really want to win this benchmark, and you are willing to go all in, then you can execute this test in less than 1ms. however this optimization would be limited to this special case, and slight modifications of the test would probably no longer trigger it.

ok, so that bitops-bitwise-and.js test was definitely the worst example of a micro-benchmark. let’s move on to something more real-world-ish in sunspider, the string-tagcloud.js test, which essentially runs a very early version of the json.js polyfill. the test arguably looks a lot more reasonable that the bitwise and test, but looking at the profile of the benchmark for some time immediately reveals that a lot of time is spent on a single eval expression (up to 20% of the overall execution time for parsing and compiling plus up to 10% for actually executing the compiled code):


looking closer reveals that this eval is executed exactly once, and is passed a jsonish string that contains an array of 2501 objects with tag and popularity fields:

    "tag": "titillation",
    "popularity": 4294967296
    "tag": "foamless",
    "popularity": 1257718401
    "tag": "snarler",
    "popularity": 613166183
    "tag": "multangularness",
    "popularity": 368304452
    "tag": "fesapo unventurous",
    "popularity": 248026512
    "tag": "esthesioblast",
    "popularity": 179556755
    "tag": "echeneidoid",
    "popularity": 136641578
    "tag": "embryoctony",
    "popularity": 107852576

obviously parsing these object literals, generating native code for it and then executing that code, comes at a high cost. it would be a lot cheaper to just parse the input string as json and generate an appropriate object graph. so, one trick to speed up this benchmark is to mock with eval and try to always interpret the data as json first and only fallback to real parse, compile, execute if the attempt to read json failed (some additional magic is required to skip the parenthesis, though). back in 2007, this wouldn’t even be a bad hack, since there was no json.parse , but in 2017 this is just technical debt in the javascript engine and potentially slows down legit uses of eval . in fact, updating the benchmark to modern javascript:

--- string-tagcloud.js.orig 2016-12-14 09:00:52.869887104 +0100 +++ string-tagcloud.js 2016-12-14 09:01:01.033944051 +0100 @@ -198,7 +198,7 @@                      replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(:?[ee][+\-]?\d+)?/g, ']').
                     replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

- j = eval('(' + this + ')'); + j = json.parse(this); 
                 return typeof filter === 'function' ? walk('', j) : j;

...yields an immediate performance boost, dropping runtime from 36ms to 26ms for v8 lkgr as of today, a 30% improvement!

$ node string-tagcloud.js.orig time (string-tagcloud): 36 ms.
$ node string-tagcloud.js time (string-tagcloud): 26 ms.
$ node -v v8.0.0-pre

this is a common problem with static benchmarks and performance test suites. today, no one would seriously use eval to parse json data (also for obvious security reasons, not only for the performance issues), but rather stick to json.parse for all code written in the last five years. in fact using eval to parse json would probably be considered a bug in production code today! so the engine writers effort of focusing on performance of newly written code is not reflected in this ancient benchmark, instead it would be beneficial to make eval unnecessarily smart complex to win on string-tagcloud.js .

ok, so let’s look at yet another example: the 3d-cube.js . this benchmark does a lot of matrix operations, where even the smartest compiler can’t do a lot about it, but just has to execute it. essentially, the benchmark spends a lot of time executing the loop function and functions called by it.


one interesting observation here is that the rotatex , rotatey , and rotatez functions are always called with the same constant parameter phi .


this means that we basically always compute the same values for math.sin and math.cos , 204 times each. there are only three different inputs:

  • 0.017453292519943295,
  • 0.05235987755982989, and
  • 0.08726646259971647

...obviously. so, one thing you could do here to avoid recomputing the same sine and cosine values all the time is to cache the previously computed values, and in fact, that’s what v8 used to do in the past, and other engines like spidermonkey still do. we removed the so-called transcendental cache from v8 because the overhead of the cache was noticeable in actual workloads where you don’t always compute the same values in a row, which is unsurprisingly very common in the wild. we took serious hits on the sunspider benchmark when we removed these benchmark-specific optimizations back in 2013 and 2014, but we totally believe that it doesn’t make sense to optimize for a benchmark while at the same time penalizing the real world use case in such a way.

3d-cube benchmark source: .

obviously, a better way to deal with the constant sine/cosine inputs is a sane inlining heuristic that tries to balance inlining and take into account different factors like prefer inlining at call sites where constant folding can be beneficial, like in the case of the rotatex , rotatey , and rotatez call sites. but this was not really possible with the crankshaft compiler for various reasons. with ignition and turbofan, this becomes a sensible option, and we are already working on better inlining heuristics .

garbage collection considered harmful

besides these very test-specific issues, there’s another fundamental problem with the sunspider benchmark: the overall execution time. v8 on decent intel hardware runs the whole benchmark in roughly 200ms currently (with the default configuration). a minor gc can take anything between 1ms and 25ms currently (depending on live objects in new space and old space fragmentation), while a major gc pause can easily take 30ms (not even taking into account the overhead from incremental marking), that’s more than 10% of the overall execution time of the whole sunspider suite! so any engine that doesn’t want to risk a 10-20% slowdown due to a gc cycle has to somehow ensure it doesn’t trigger gc while running sunspider.


there are different tricks to accomplish this, none of which has any positive impact in the real world as far as i can tell. v8 uses a rather simple trick: since every sunspider test is run in a new <iframe> , which corresponds to a new native context in v8 speak, we just detect rapid <iframe> creation and disposal (all sunspider tests take less than 50ms each), and in that case perform a garbage collection between the disposal and creation, to ensure that we never trigger a gc while actually running a test. this trick works pretty well, and in 99.9% of the cases doesn’t clash with real uses; except, every now and then, it can hit you hard if for whatever reason you do something that makes you look like you are the sunspider test driver to v8, then you can get hit hard by forced gcs, and that can have a negative effect on your application. so rule of thumb: don’t let your application look like sunspider!

i could go on with more sunspider examples here, but i don’t think that’d be very useful. by now it should be clear that optimizing further for sunspider above the threshold of good performance will not reflect any benefits in the real world. in fact, the world would probably benefit a lot from not having sunspider anymore, as engines could drop weird hacks that are only useful for sunspider and can even hurt real-world use cases. unfortunately, sunspider is still being used heavily by the (tech) press to compare what they think is browser performance, or even worse, to compare phones! so there’s a certain natural interest from phone makers and also from android, in general, to have chrome look somewhat decent on sunspider (and other nowadays meaningless benchmarks fwiw). the phone makers generate money by selling phones, so getting good reviews is crucial for the success of the phone division or even the whole company, and some of them even went as far as shipping old versions of v8 in their phones that had a higher score on sunspider, exposing their users to all kinds of unpatched security holes that had long been fixed and shielding their users from any real-world performance benefits that come with more recent v8 versions!

galaxy s7 and s7 edge review: samsung&apos;s finest get more polished source: galaxy s7 and s7 edge review: samsung's finest get more polished, .

if we as the javascript community really want to be serious about real world performance in javascript land, we need to make the tech press stop using traditional javascript benchmarks to compare browsers or phones. i see that there’s a benefit in being able to just run a benchmark in each browser and compare the number that comes out of it, but then please, please use a benchmark that has something in common with what is relevant today, i.e. real-world web pages. and, if you feel the need to compare two phones via a browser benchmark, please at least consider using speedometer .

cuteness break!

i always loved this in myles borins ’ talks, so i had to shamelessly steal his idea. anyway, hope that refreshed your pallate. and now that we've recovered from the sunspider rant, we can all get back to whatever it is we were doing. tomorrow, we'll continue on looking into the other classic benchmarks…

stay tuned for part three. here's part one in case you missed it.

Published at DZone with permission of Benedikt Meurer, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.