HTML and CSS Reference
In-Depth Information
LLVM, Emscripten translates C or C++ into JavaScript so it can run directly from web browsers. You can think of
Emscripten as the sum of three components:
A compiler from LLVM IR into a subset of JavaScript.
A set of convenience tools that make it easy to use LLVM and Clang to compile C++ into
JavaScript.
A standard set of libraries and APIs, like libc, libc++, SDL, OpenGL, and zlib, to ease porting efforts.
Before we dive any deeper, I can hear you exclaim “But isn't JavaScript much slower than native code? Why
would I want to compile my fast native code into slow JavaScript? How could my game's performance possibly be
acceptable?”
We will dig into how compiling C++ to JavaScript has acceptable performance in more detail later, but let's look
at some numbers first. In 2011, C++ compiled to JavaScript ran at less than 10% of the speed of the equivalent native
code—a 10x slowdown or more, depending on the code. That's pretty terrible, but times have changed.
Table 18-1 shows the results from a software skeletal animation benchmark I ran in 2011, comparing vertex
transform rate between a scalar floating point native implementation and the equivalent Emscripten-compiled
program.
Table 18-1. Native vs. Emscripten Performance in 2011
Vertices/sec
Slowdown
Native gcc 4.2
63355501
1
Emscripten
5184815
12.2
Since then, JavaScript engines have learned to recognize and optimize the particular style of code generated by
Emscripten and other C++-to-JavaScript compilers. Table 18-2 is the same benchmark run today, this time having
Emscripten generate the asm.js subset of JavaScript.
Table 18-2. Native vs. Emscripten Performance in 2014
Vertices/sec
Slowdown
Native gcc 4.2
61215975
1
Firefox 27 asm.js
32282000
1.90
Chrome 32 asm.js
24036000
2.55
The absolute numbers differ from 2011's as the benchmark was run on a different machine, so focus on the
relative slowdown. With Emscripten compiler and JavaScript engine improvements, C++ compiled to JavaScript can
run at 40-50% of native speed, a huge improvement from the 2011 numbers.
Emscripten-generated JavaScript, run in a browser, will likely never match native code performance, as the Web
is expected to be secure, and security sandboxes generally impose some overhead. However, it's conceivable that,
in time, C++ code compiled into JavaScript for the browser could run with a mere 5-15% overhead relative to native,
given that Google's Native Client code performs within 5% of native. There is a fair amount of room for browser
optimization technology to improve. You can track cross-browser asm.js benchmarks at http://arewefastyet.com/ .
 
Search WWH ::




Custom Search