Software Performance Engineering

Every time we build software we have functional requirements. Maybe these functional requirements are not well defined but they are good enough to start prototyping and you refine them as you go. After all, the functional requirements describe what you have to build. Sometimes, you have additional requirements that describe how your software system should operate, rather than how it should behave. We call them non-functional requirements. For example if you build a web site, a non-functional requirement can define the maximum page response time. In this post I am not going to write about the SPE approach, but rather about the more general term of software performance engineering.


Anytime a new technology emerges people want to know how fast it is. We seem obsessed with this question. Once we understand the basic scenarios where a new tech is applicable we start asking questions about its performance. Unfortunately, talking about performance is not easy because of all misunderstanding around it.

Not quick. Efficient.

Let’s set up some context. With any technology we are trying to solve some problem, not everything. In some sense, any technology is bound to the time. In general, nowadays we solve different problems than 10 years ago. This is so obvious in the IT industry as it changes so fast. Thus, when we talk about given technology it is important to understand where it comes from and what are the problems it tries to solve. Obviously, a technology cannot solve all current problems and there is no best technology for everything and everybody.

We should understand another important aspect as well. Usually when a new technology emerges it has some compatibility with an older one. We don’t want people to learn again how to do trivial things. Often this can have big impact on performance.

Having set up the context, it should be clear that the interpreting performance results is also time bound. What we have considered fast 5 years ago, may not be fast any longer. Now, let’s try to describe informally what performance is and how we try to build performant software. Performance is a general term describing various system aspects such as operation completion time, resource utilization, throughput, etc. While it is a quantitative discipline it does not define itself any criterion what is good or bad performance. For the sake of this post, this definition is good enough to understand why performance is important in say, algorithmic trading. In general, there is a clear connection between performance and cost.

IT Industry-Education Gap

Performance issues are rarely measured in a single value (e.g. CPU utilization) and thus they are difficult to understand. These problems become even more difficult in distributed and parallel systems. Despite the fact that performance is important and difficult problem, most universities and other educational facilities fail to prepare their students so they can avoid and efficiently solve performance issues. The IT industry has recognized this fact and there are companies like Pluralsight, Udacity and Coursera that offer additional training on this topic.

In the rare cases where students are taught on localizing and solving performance issues, they use outdated textbooks from ’80s. Current education cannot produce well-trained candidates mostly because the teachers have outdated knowledge. On the other hand, many (online) education companies offer highly specialized performance courses in say, web development, C++, Java or .NET, which cannot help students to understand the performance issues in depth.

Sometimes the academia tries to help the IT industry providing facilities like cache-oblivious algorithms or QN models but abstracting real hardware often produces suboptimal solutions.

Engaging students in real-life projects can prepare them much better. It doesn’t matter whether it is an open-source project or a collaboration with the industry. At present, students just don’t have the chance to work on a big project and thus miss the opportunity to learn. Not surprisingly the best resources on solving performance issues are various blogs and case studies from big companies like Google, Microsoft, Intel and Twitter.

Performance Engineering

Often software engineers have to rewrite code or change system architecture because of performance problems. To mitigate such expensive changes, many software engineers try to employ various tools and practices. Usually, these practices can be formalized in the form of an iterative process which is part from the development process itself. A common simplified overview of such iterative process might be as follows:

  • identify critical use cases
  • select a use case (by priority)
  • set performance goals
  • build/adjust performance model
  • implement the model
  • gather performance data (exercise the system)
  • report results

Different performance frameworks/approaches emphasize on different stages and/or techniques for modelling. However, what they all have in common is that it is an iterative process. We set up performance goals and perform quantitative measurements. We repeat the process until we meet the performance goals.

Most performance engineering practices heavily rely on tools and automation. Usually, they are part from various CI and testbed builds. This definitely streamlines the process and helps the software engineers. Still, there is a big caveat. Building a good performance model is not an easy task. You must have a very good understanding of the hardware and the whole system setup. The usual way to overcome this problem is to provide small, composable model templates for common tasks so the developer can build larger and complex models.

In closing I would say that there isn’t a silver bullet when it comes to solving performance issues. The main reason to make solving performance issues difficult is that it requires a lot of knowledge and expertise from both software and hardware areas. There are a lot of places for improvement both in the education and the industry.

What’s New in Chakra JavaScript Engine

A few weeks ago I decided to install Windows 10 Mobile Insider Preview on my Nokia Lumia 630 and played a little bit with it. Since then, I have completely forgotten about it until yesterday when I saw a notification for pending software update (10.0.12562.84). So I grabbed the opportunity to see what changed in Chakra JavaScript engine and JsRT API.


I am going highlight only some of the architectural changes in Chakra, for more information you can read MSDN documentation. Firstly, Microsoft decided to create new chakra.dll library and keep the old jscript9.dll library for compatibility reasons. This is a good decision because it allows shorter release cycles and provides some space for experimentation as well. Secondly, it seems that Microsoft is all into performance optimizations right now. Some of the most important optimizations are:

  • concurrent JIT compiler
  • new simple JIT compiler (when bailout happens)
  • improved polymorphic inline cache
  • equivalent object type specialization
  • bounds checking elimination (array optimization)
  • minified code optimization (sounds interesting and very promising)
  • concurrent mark-and-sweep GC (mark phase)

Lastly, with the upcoming ECMAScript 6 Microsoft decided to provide better support for it which is a big win for everybody.


This is where it becomes interesting. As I work on NativeScript project, I would like to access WinRT APIs from JavaScript. In fact, Microsoft already supports this scenario in WinJS but I am interested in accessing all WinRT APIs and being able to build XAML based UI from JavaScript. Last September I blogged how to embed Chakra in Windows Phone 8.1 but back then this scenario was practically not supported by Microsoft. There wasn’t even jscript9.lib import library for ARM.

I am happy to say that those days are gone. Now, JsRT provides better support for WinRT projections. This is done through the following APIs:

  • JsProjectWinRTNamespace
  • JsInspectableToObject
  • JsObjectToInspectable

Let’s see how this works (I assume you have already installed Windows 10 Technical Preview and Visual Studio 2015 RC). Create new WinRT library project (Visual C++ -> Windows -> Windows Universal -> Windows Runtime Component). In my case I named it WindowsRuntimeComponent1 and created a simple Greeter class as follows.

namespace WindowsRuntimeComponent1
    public ref class Greeter sealed
        Platform::String^ SayHello()
            return ref new Platform::String(L"Hello");

Create an empty app (Visual C++ -> Windows -> Windows Universal -> Blank App) and add reference to the WindowsRuntimeComponent1 project. You have to define the macro USE_EDGEMODE_JSRT  in order to use the new JsRT API and link against chakrart.lib as well. Projecting WinRT classes is as easy as follows.

JsErrorCode err = JsProjectWinRTNamespace(L"WindowsRuntimeComponent1");
assert(JsNoError == err);

Now we are ready to consume the projected WinRT classes from JavaScript.

var g = new WindowsRuntimeComponent1.Greeter();
var s = g.sayHello();

I have to say that the debugging experience is almost perfect. I say “almost” only because I don’t see script debugging for ARM devices. I guess since this is Visual Studio 2015 RC it is a kind of expected. Also, you can always use script debugger on Windows Phone emulator since it is running x86 code.

You can find the sample project at GitHub.


Using the new JsRT together with Windows 10 Universal Application Platform (UAP) makes it easy to write apps that use JavaScript scripting. The good thing is that UAP guarantees that your apps will work across all kind of devices. There are some important limitations though:

  • cannot use XAML types (I guess it is still related to WebHostHidden attribute)
  • cannot extend types from JavaScript (again related to XAML)
  • cannot access Chakra in WinJS apps from WinRT components

I guess if you don’t want to build JavaScript/native bridges then the new JsRT is good enough. Resolving the above-mentioned issues will allow writing much more sophisticated apps though. Right now, you can use JsRT for simple scripting and nothing else. Making Chakra engine an open-source project will solve these and other issues. It will allow people to contribute to and customize the engine. Will it ever happen? Only time will tell.

NativeScript Performance – Part 2

The last two weeks I was busy with measuring and optimizing the performance of NativeScript for Android. My main focus was the application startup time and I would like to share some good news.


Let’s first see the results and then I will dig into the details. As in the previous tests I uses the same test devices:

  • Device1 – Nexus 5, Android 4.4.1, build KOT49E
  • Device2 – Nexus 6, Android 5.0.1, build LRX22C

I used the same application as well. Here are the results:

  • For Device1 the first startup time was reduced from average 3.1419 seconds to average 2.8262 seconds (10% improvement) [*]
  • For Device2 the first startup time was reduced from average 3.541 seconds to average 3.3147 seconds (6% improvement) [*]


Before I dig into the details, I would like to give you a quick reminder how I measured the times. As in the previous tests I used the built-in time/perf info that Android ActivityManager provides. It is not the best measuring tool but it is good enough for our purposes.

After detailed profiling with DDMS and NDK profilers I identified two areas for improvements:

  • asset extraction
  • proxy property access


The old implementation for asset extraction was based on AssetManager. While its API is very convenient, it is not well suited for optimal memory allocation. As a result using AssetManager along with* classes generates a lot of temporary objects which triggers the GC quite often. The solution we chose is to use libzip C++ library. It is fast and more importantly it doesn’t mess with the GC.

For applications with size similar to the test app using libzip doesn’t help much. The actual improvement is around 30-40 milliseconds. However, for big apps (e.g. 500+ files) libzip really shines. You can easily get improvement of 300-500ms, and in some scenarios more than a second. This was a good reason to reimplement the Java code into C++ and give NativeScript the ability to scale really well.

Java Object Wrappers

Proxies are an experimental ECMAScript 6 feature. In V8 (and for the matter of fact in any other JavaScript engine), direct property access is much faster than direct proxy access. This is easily understandable when you think how the JIT compiler emits the code to access traditional properties. Also, while proxies are good for scripting simple object access they don’t scale in more complex scenarios. With the time it becomes harder to implement the correct dispatch logic.

I am glad to say that we now use plain JavaScript objects to wrap Java objects. We also build the correct prototype chain to map Java class hierarchy. This give us an excellent opportunity to cache runtime objects at more granular level. And as we are going to see, caching changes everything.

While using libzip helped a little bit, it is easy to do the math and see that using prototype chains is the main factor for the improved startup time.

Let’s see how the new caches impact other scenarios. Take a look at the following code fragment.

var JavaDate = java.util.Date;
var start = new Date();
for (var i=0; i<10000; i++) {
    var d1 = new JavaDate();
    var d2 = new JavaDate();
var end = new Date();
console.log("time=" + (end.getTime() - start.getTime()));

This is not a real world scenario. I wrote this code for sole test purposes. My intent here is to exercise some Java intensive code. Also, note that using JavaScript Date.getTime is not the best way to measure time, but as we are going to see it is good enough for our purposes.

Here are the results.

  • On Device1 – using proxy objects it takes more than 12.5 seconds, using prototype chain it takes less than 2.6 seconds
  • On Device2 – using proxy objects it takes more than 11.6 seconds, using prototype chain it takes less than 2.2 seconds

In my opinion, there is no need for any further or more precise benchmarks. Simply put, using prototype chains along with proper caching is much faster than proxy objects.

Further Improvements

So far, we saw that the first startup of a simple application like CutenessIO takes around 3 seconds. Can we make it faster?

First, we have to set some reasonable expectations. Let’s see how fast HelloWorld applications written in Java and NativeScript start up. For the Java version I used the standard Eclipse project template (which is very similar to the one in Android Studio). I stripped all things like menus and fancy themes. My main goal was the make it as simple as possible (which is not much different from the standard empty project). I did the same for the NativeScript project.

Here are the results.

  • On Device1 – Java 200 milliseconds[*], NativeScript 641.5 milliseconds[*]
  • On Device2 – Java 333.5 milliseconds[*], NativeScript 875.3 milliseconds[*]

So, we have to investigate where the difference comes from. For the purpose of this article, I am going to pick Device1 (the analysis for Device2 is the same).

Let’s analyze a particular run.

  • Time for loading libNativeScript library: 7ms
  • Time for extracting assets: 30ms
  • Time for V8 initialization: 150ms
  • Time for calling Application.onCreate in JavaScript: 60ms
  • Time for calling Activity.onCreate in JavaScript: 100ms
  • Time from Application object initialization to Activity initialization: 510ms
  • Time to display main activity: 658ms

As we can see, the total time of asset extraction and V8 initialization is 180ms which is roughly the time needed for pure Java application to start. So far, it seems unlikely to reduce this time.

The total time spent in running JavaScript 160ms. This is a bit surprising. I would love to see the time spent in V8 to be, say, 400ms because this would mean that running JavaScript is 78% (400/510) of all time. High percentage of time spent inside in V8 is a good thing because this will give us an opportunity to optimize the performance. However, this would not be the case for most applications. We can think of NativeScript as a way to command Java world from JavaScript. Hence, most of the work is done in Java. That’s the nature of NativeScript.

So, we spent 160ms running a few lines of JavaScript. Can we do better? A careful analysis showed that most of this time is spent in JNI infrastructure calls and data marshalling. It seems hard to reduce it, but not unlikely. A possible option is to tweak V8 engine and/or use libffi to generate thunks.

Another 200ms is spent in some run-once pluming code. With a little effort, we could refactor the runtime to support components/modules and gain some performance. Finally, some time is spent inside the Java GC.

In closing, I would say that currently NativeScript for Android is performing well. There are no major performance issues. The current implementation is approaching the point where no big performance wins can be easily achieved. But easy is not interesting 😉 Stay tuned.

On NativeScript Performance


Last week NativeScript made it into public beta and just for a few days we got tremendous amount of feedback. One question that came up over and over again was, “How do NativeScript Apps Perform”?  In this post, I want to explain the details behind performance and share some great news with you about the upcoming release of NativeScript.

How it started

As other new projects NativeScript started from the idea to take a new look at the cross-platform mobile development with JavaScript. In the beginning, we had to determine if the concept of NativeScript was even feasible.  Should we translate JavaScript into Java?  What about Objective-C back into JavaScript?  During this exploratory phase, we learned that the answer was actually much simpler than this thanks to the JavaScript bridge that exists for both iOS and Android.  Well, thanks to Android fragmentation, this is only partially true.  Let me explain…


Working on a project like NativeScript is anything but easy. There are many challenges imposed by working with two very different runtimes like Dalvik and V8. Add the restricted environment in Android and you will get the idea. Controlling object lifetime when you have two garbage collectors, efficient type marshalling, lack of 64bit integers in JavaScript, correctly working with different UTF-8 encodings, and overloaded method resolution, just to name a few. All these are nontrivial problems.

Statically Generated Bindings

One specific problem is the extending/subclassing of Java types from JavaScript. It is astonishing how a simple task like working with a UI widget becomes a challenging technical problem. It takes no longer to look than the Button documentation and its seemingly innocent example.

button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Perform action on click

While the Java compiler is there for you to generate an anonymous class that implements View.OnClickListener interface there is no such facility in JavaScript. We solved this problem by generating proxy classes (bindings). Basically we generated *.java source files, compiled them to *.class files which in turn were compiled to *.dex files. You can find these *.dex files in assets/bindings folder of every NativeScript for Android project. The total size of these files is more than 12MB which is quite a lot.

Here begins the interesting part. Android 5 comes with a new runtime (ART). One of major changes in ART is the ahead-of-time (AOT) compiler. Now you can imagine what happens when the AOT compiler has to compile more than 12MB *.dex files on the very first run of any NativeScript for Android application. That’s right, it takes a long time. The problem is less apparent in Android 4.x but it is still there.

Dynamically Generated Bindings

The solution is obvious. We simply need to generate bindings in runtime instead of compile time. The immediate advantages are that we will generate bindings only for those classes that we actually extend in JavaScript. Lesser the bindings, lesser the work for the AOT compiler.

We started working on the new binding generator right after the first private beta. We were almost done for the public beta. However, almost doesn’t count. We decided to play safe and release the first beta with statically generated bindings. The good news is that the new binding generator is already merged in the master branch (only two days after the public beta announcement).

Today I ran some basic performance tests on the following devices:

  • Device1 – Nexus 5, Android 4.4.1, build KOT49E
  • Device2 – Nexus 6, Android 5.0.1, build LRX22C

For the tests I used the built-in time/perf info that Android OS provides. You probably have seen similar information in your logcat console.

I/ActivityManager(770): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.tns/.NativeScriptActivity} from pid 1030
I/ActivityManager(770): Displayed com.tns/.NativeScriptActivity: +3s614ms

Here are the results:

  • For Device1 the first start-up time was reduced from average 6.0761 seconds to average 3.1419 seconds
  • For Device2 the first start-up time was reduced from average 39.384 seconds to average 3.541 seconds

A consequential start-up time for both devices is ~2.5 or less seconds.

What’s next

There is a lot of room for performance improvement. Currently NativeScript for Android uses JavaScript proxy object to get a callback when Java field is accessed or Java method is invoked. The problem is that proxy objects (interceptors) are not fast. We plan to replace them with plain JavaScript objects that have properly constructed prototype chain with accessors instead of interceptors. Another benefit of using prototype chains with accessors is that we will support JavaScript instanceof operator.

Another area for improvement is the memory management. Currently, we generate a lot of temporary Java objects which may kick the Java GC unnecessary often. Moving some parts of the runtime from Java to C++ is a viable option that we are going to explore.


In closing, I would like to say that we are astounded by how popular NativeScript has become in such a short amount of time. We have learned so much in the building the NativeScript runtime, and our experience in that process helps us improve NativeScript every single day.  We’re looking forward to version 1. Building truly native mobile applications with native performance using JavaScript is the future, and the future is now.

Java Class Inheritance in NativeScript for Android

One of the more advanced scenarios in NativeScript for Android is the inheritance of Java classes. Let’s take a look at the following example.

// app.js
var MyButton = android.widget.Button.extend({
    setEnabled: function(enabled) {
        // do something
var btn = new MyButton(context);

(Please note that at the time of writing NativeScript is in private beta version and the syntax may change in the future.)

This is a minimalistic example how to define a new derived class with JavaScript. In this example we define new class MyButton that inherits from android.widget.Button and overrides setEnabled method. Behind the scenes NativeScript for Android will generate a new Java class as follows.

public class <runtime_generated_name> extends android.widget.Button {
    public void setEnabled(boolean enabled) {
        Object[] params = new Object[1];
        params[0] = enabled;
        NativeScriptRuntime.callJSMethod(this, "setEnabled", params);

This class serves as a simple proxy that calls the JavaScript implementation of setEnabled method. For the curious ones the method callJSMethod is defined as native and is used to dispatch the method invocation to the JavaScript engine.

public class NativeScriptRuntime {
    public static native Object callJSMethod(Object obj, String methodName, Object[] params);

So far we didn’t talk about the class’ <runtime_generated_name>. This name is generated from the following things:

  • the name of the base class
  • the name of the JavaScript file in which the class is defined
  • the line number
  • the column number

Let’s assume that MyButton is defined in app.js file on line 21 and column 38. In this case the generated class name may be something like <package_prefix>.android_widget_Button_app_L21_C38 where <package_prefix> is some hard-coded package name.

For more advanced scenarios NativeScript for Android allows you to overwrite the generated class name. You can do that using the full extend signature.

extend(<class_name>, implementationObject)

Usually you can omit class_name argument and let NativeScript to generate it for you.

There is one important difference between Java and JavaScript though. Java generates derived classes at compile time while NativeScript generates derived classes at runtime. As a consequence Java generates a derived class exactly once while NativeScript can execute extend function multiple times. This means that NativeScript must performs validation checks before it generates a class.

There are many approaches to this problem. As NativeScript for Android is in private beta we are still discussing what the validation checks should be. Here is a simplified diagram of one possible approach.


We basically can check whether extend is called with the same name and implementation object before and return the cached class. In this case it seems reasonable to freeze the implementation object on the first call in order to guarantee that multiple instances of a single extended class will have the same runtime behavior.

In closing, I would like to say that there is not much time until the official release of NativeScript. Today I showed you just one possible approach how to extend a Java class from JavaScript. There are other options as well. If you think there are better solutions please do not hesitate and leave a comment.

Efficient IO in Android

What could be simpler than a file copy? Well, it turned out that I underestimated such an easy task.

Here is the scenario. During the very first NativeScript for Android application startup the runtime extracts all JavaScript asset files to the internal device storage. The source code is quite simple and it was based on this example.

static final int BUFSIZE = 100000;

private static void copyStreams(InputStream is, FileOutputStream fos) {
    BufferedOutputStream os = null;
    try {
        byte data[] = new byte[BUFSIZE];
        int count;
        os = new BufferedOutputStream(fos, BUFSIZE);
        while ((count =, 0, BUFSIZE)) != -1) {
            os.write(data, 0, count);
    } catch (IOException e) {
        Log.e(LOGTAG, "Exception while copying: " + e);
    } finally {
        try {
            if (os != null) {
        } catch (IOException e2) {
            Log.e(LOGTAG, "Exception while closing the stream: " + e2);

It is important to note the in our code BUFSIZE constant has value 100000 while in the original example the value is 5192. While this code works as expected it turns out it is quite slow.

In our scenario we extract around 200 files and on LG Nexus 5 device it takes around 5.75 seconds. This is a lot of time. It turned out that most of this time is spent inside the garbage collector.

D/dalvikvm(8611): GC_FOR_ALLOC freed 265K, 2% free 17131K/17436K, paused 8ms, total 8ms
D/dalvikvm(8611): GC_FOR_ALLOC freed 398K, 4% free 16930K/17636K, paused 11ms, total 11ms
D/dalvikvm(8611): GC_FOR_ALLOC freed 197K, 4% free 16930K/17636K, paused 7ms, total 7ms
... around 650 more lines

The first thing I optimized was to make data variable a class member.

static final int BUFSIZE = 100000;

static final byte data[] = new byte[BUFSIZE];

private static void copyStreams(InputStream is, FileOutputStream fos) {
   // remove 'data' local variable

I thought this will solve the GC problem but when I ran the application I was greeted with the following familiar log messages.

D/dalvikvm(8408): GC_FOR_ALLOC freed 248K, 2% free 17212K/17496K, paused 7ms, total 8ms
D/dalvikvm(8408): GC_FOR_ALLOC freed 417K, 4% free 17029K/17696K, paused 8ms, total 8ms
D/dalvikvm(8408): GC_FOR_ALLOC freed 199K, 4% free 17029K/17696K, paused 7ms, total 7ms
... around 330 more lines

This time it took around 2.25 seconds to extract the files. And the GC kicked 330 times instead of 660 times. Well, it was better but it wasn’t what I wanted. The GC kicked twice less than the previous example but still it was too much.

The next thing I tried is to set BUFSIZE to 4096 instead of 100000.

static final int BUFSIZE = 4096;

This time it took around 0.85 seconds to extract the assets and the GC kicked 8 times.

D/dalvikvm(8218): GC_FOR_ALLOC freed 323K, 3% free 17137K/17496K, paused 8ms, total 8ms
D/dalvikvm(8218): GC_FOR_ALLOC freed 673K, 5% free 16947K/17684K, paused 8ms, total 9ms
D/dalvikvm(8218): GC_FOR_ALLOC freed 512K, 5% free 16947K/17684K, paused 8ms, total 9ms
... just 5 more lines

It was a nice improvement but I thought it should be faster than this. I was still puzzled with this relatively high level of GC activity so I decided to read the online documentation.

A specialized OutputStream for class for writing content to an (internal) byte array. As bytes are written to this stream, the byte array may be expanded to hold more bytes.

I’ve should read this before I start. It was a good lesson to me.

Once I knew what happens inside BufferedOutputStream internals I decided just not to use it. I call write method of FileOutputStream and voilà. The time to extract the assets is around 0.65 seconds and the GC kicks 4 times at most.

Out of curiosity I decided to try to bypass the GC using libzip C library. It took less than 0.2 seconds to extract the assets. Another option is to use AAssetManager class from NDK but I haven’t tried it yet. Anyway, it seems that IO processing is one of those areas where unmanaged code outperforms Java.

First Impressions using Windows 10 Technical Preview for phones

Windows 10 Technical Preview for phones was released two days ago and today I decided to give it a try. The installation process on my Nokia 630 was very smooth and completed for about 30 minutes including the migration of the old data. Finally, I ended up with WP10 OS version 9941.12498.


After I used WP10 for about 6 hours I can say that this build is quite stable. The UI and all animations are very responsive. So far I didn’t experience any crashes. The only glitch I found is that the brightness setting is not preserved after restart and it is set automatically to HIGH. All my data including photos, music and documents were preserved during the upgrade.

There are many productivity improvements in WP10. Action Center and Settings menu are much better organized. It seems that IE can render some sites better than before though I am not sure if it is the new IE rendering engine or just the site’s html has been optimized.

I checked to see whether there are changes in Chakra JavaScript engine but it seem the list of exported JsRT functions is the same as before. The actual version of jscript9.dll is 11.0.9941.0 (fbl_awesome1501.150206-2235).

I tested all of my previously installed apps (around 60) and they all work great. The perceived performance is the same, except for Lumia Panorama which I find slower and Minecraft PE which I find faster.

There are many new things for the developers as well. I guess one of the most interesting changes in WP10 is the improved speech support API. Using the speech API is really simple.

using Windows.Phone.Speech.Synthesis;

var s = new SpeechSynthesizer();
s.SpeakTextAsync("Hello world");

WP10 comes with two predefined voice profiles.

using using Windows.Phone.Speech.Synthesis;

foreach (var vi in InstalledVoices.All)
    var si = new SpeechSynthesizer();
    await si.SpeakTextAsync(vi.Description);

The actual values of vi.Description are as follows.

Microsoft Zira Mobile - English (United States)
Microsoft Mark Mobile - English (United States)

You can hear how Zira and Mark actually sound below.

I find Mark’s voice a little bit more realistic.

This is all I got for today. In closing I would say it seems that WP10 has much more to offer. Stay tuned.

Object Oriented Programming: An Evolutionary Approach

This post is not about the book Object Oriented Programming: An Evolutionary Approach by Brad Cox. I decided to use the book’s title because the author nailed the connection between software and evolution. It is a good book, by the way. I recommend it.

Last week a coworker sent me a link to the React.js Conf 2015 Keynote video in which they introduced React Native. Because I work on NativeScript, I was curious to see how Facebook solves similar problems as we do. So, I finally got some time and watched the video. The presentation is short and probably the most important slide is the following one.


But this blog post is not about React Native. The thing that triggered me to write is something that the speaker said (the transcription is mine).

This is a component. This, we feel, is the proper separation of concerns for applications.

I couldn’t agree more. Components have been around for many years (don’t get me wrong, I am not bringing up one of those everything new is well-forgotten old themes). Yet, components and component-based development are not as widely accepted as I think they should be. It is probably because so many people/companies saw a value in software components and started defining/building them as they think it is the right way. And this process brought all the confusion what a component really is.

Beside the fact that the term component is quite overloaded it is important to note that many had tried to (re)define it in different times and environments/contexts. Nevertheless, some properties of software components were defined in exactly the same manner during the 70’s, 80’s, 90’s and later. Let’s see what these properties are.

  • binary standard/compatibility
  • separation of interface and implementation
  • language agnostic

These are some of the fundamental properties of any software component. More recent component definitions include properties like:

  • versioning
  • transaction support
  • security
  • etc.

But this blog post is not about software components either. It is about software evolution. We can define software evolution as a variation in software over the time. This definition is not complete but it is good enough. It can be applied on different levels, whether it is the software industry as a whole or a small application. It is important to say that software evolution is a result of our understanding about software, including an exact knowledge, culture and beliefs, at any point of time. We can reuse the analogy of terms like mutation, crossover, hybrid and so on to describe processes in software evolution.

Combining different ideas is one of the primary factor for software evolution. And this is where we need software components. There is a common comparison between software components and LEGO blocks. The analogy of software genes might be another alternative. An application DNA is defined by its genes.

Software evolution is not a linear process. Do you remember Twitter’s dance between client-side and server-side rendering? It is a great example of survival of the fittest principle. So, what will be the next thing in software evolution? I don’t think anybody know the answer. So far, the software components seem to be a practical way to go. Seeing big companies like Facebook to emphasize on composability is a good sign.

The best way to predict your future is to create it.
– Abraham Lincoln

The Quiet Horror of instanceof Operator

During the last months I was busy with NativeScript more than ever. While my work keeps me busy with embedding V8 JavaScript engine I rarely have the chance to write JavaScript. Recently I had to deal with mapping Java OOP inheritance into JavaScript and more specifically I had to fix a failing JavaScript unit test which uses instanceof operator. So I grabbed the opportunity to dig more into instanceof internals.

It is virtually impossible to talk about instanceof operator without mentioning typeof operator first. According MDN documentation

The typeof operator returns a string indicating the type of the unevaluated operand.

As described typeof operator does not seem useful. Probably the most interesting thing the use of unevaluated word. This allows us to test whether particular symbol is defined. For example

if (typeof x !== 'undefined')

will execute without ReferenceError even when x is not present.

Let’s see instanceof documentation

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.

After digging into instanceof operator I was even more puzzled. While typeof operator was introduced since the first edition of ECMAScript it seems that language designer(s) didn’t have clear idea about instanceof operator. It is mentioned as a reserved keyword in the second edition of ECMAScript and it is finally introduced into the third edition of ECMAScript. The operator definition is clear but I have troubles finding meaningful uses. Let’s see the following common example.

if (x instanceof Foo) {;

I feel uneasy with the assumption that if x has Foo‘s prototype somewhere in its prototype chain then it is safe to assume that bar exists. Mixing properties of nominal type system with JavaScript just doesn’t seem intuitive to me. I guess there are some practical scenarios where typeof and instanceof operators are useful but my guess is that their number is limited.

Embedding Chakra JavaScript Engine on Windows Phone

Today I am going to show you how to embed Chakra JavaScript engine in Windows Phone 8.1 app. Please note that at the time of writing this app won’t pass Microsoft Windows Store certification requirements. I won’t be surprised though if Microsoft reconsider their requirements in future.

Last year Microsoft released JsRT which exposes C-style API for embedding Chakra JavaScript engine. To use the API you only need to include jsrt.h and add a reference to jsrt.lib. On my machine the header file is located at

C:\Program Files (x86)\Windows Kits\8.1\Include\um\jsrt.h

and the lib files (for x86 and x64 accordingly) are located at

C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86\jsrt.lib
C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x64\jsrt.lib

Curiously, there is no jsrt.lib for ARM architecture. It is even more interesting that JsRT is not exposed in Windows Phone SDK. E.g. you won’t find jsrt.h file in

C:\Program Files (x86)\Windows Phone Kits\8.1\Include

neither you will find jsrt.lib in

C:\Program Files (x86)\Windows Phone Kits\8.1\lib\ARM
C:\Program Files (x86)\Windows Phone Kits\8.1\lib\x86

However this shouldn’t discourage us. The first thing we should check is that JsRT API is exposed on Windows Phone 8.1. I know it is there because IE11 shares same source code for desktop and mobile and because Windows Phone 8.1 supports WinRT programming model. Anyway, let’s check it.

Find flash.vhd file. On my machine it is located at

C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.1\Emulation\Images

Use Disk Management and attach flash.vhd file via Action->Attach VHD menu. Navigate to \Windows\System32 folder on MainOS partition and copy JSCRIPT9.DLL somewhere. Open Visual Studio command prompt and run the following command

dumpbin /exports JSCRIPT9.DLL >jscript9.def

Open jscript9.def file in your favorite editor and make sure you see the full JsRT API listed here. Edit the file so it becomes like this one Run the following command from the Visual Studio command prompt

lib /def:jscript9.def /out:jsrt.lib /machine:ARM

This will generate import library so you can use all exports defined in JSCRIPT9.DLL library. We are almost ready.

We generated jsrt.lib import library for ARM architecture, what’s next? In order to use jsrt.h header in our Windows Phone 8.1 project we must edit it a little bit. First copy it and its dependencies to your project. Here is the list of all the files you should copy

  • activdbg.h
  • activprof.h
  • ActivScp.h
  • DbgProp.h
  • jsrt.h

In case you don’t want JavaScript debugging support you can copy jsrt.h file only and replace all pointers to the interfaces from ActiveScript API with void*. Once you copy the the header files you must edit them to switch to Windows Phone API. To do so, you have to replace WINAPI_PARTITION_DESKTOP with WINAPI_PARTITION_PHONE_APP. It may sound like a lot of work but it is just a few lines change. You can see the change here.

That’s it. Now you can use the new header and lib files in your project. You can find the full source code at

In closing I would like to remind you that at present this app won’t pass Windows Store certification requirements. Here is the list of the requirement violations

Supported API test (FAILED)
    This API is not supported for this application type - Api=CoGetClassObject. Module=api-ms-win-core-com-l1-1-1.dll. File=ChakraDemoApp.exe.
    This API is not supported for this application type - Api=JsCreateContext. Module=jscript9.dll. File=ChakraDemoApp.exe.
    This API is not supported for this application type - Api=JsCreateRuntime. Module=jscript9.dll. File=ChakraDemoApp.exe.
    This API is not supported for this application type - Api=JsDisposeRuntime. Module=jscript9.dll. File=ChakraDemoApp.exe.
    This API is not supported for this application type - Api=JsRunScript. Module=jscript9.dll. File=ChakraDemoApp.exe.
    This API is not supported for this application type - Api=JsSetCurrentContext. Module=jscript9.dll. File=ChakraDemoApp.exe.
    This API is not supported for this application type - Api=JsStartDebugging. Module=jscript9.dll. File=ChakraDemoApp.exe.
    This API is not supported for this application type - Api=JsStringToPointer. Module=jscript9.dll. File=ChakraDemoApp.exe.

Hopefully Microsoft will revisit their requirements.