<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Damien Diehl on Medium]]></title>
        <description><![CDATA[Stories by Damien Diehl on Medium]]></description>
        <link>https://medium.com/@Damien.Diehl?source=rss-735914bc25fd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0FR__i4L5t6wurFhjCoUKA.jpeg</url>
            <title>Stories by Damien Diehl on Medium</title>
            <link>https://medium.com/@Damien.Diehl?source=rss-735914bc25fd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:12:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Damien.Diehl/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reified Generics & Inline Functions]]></title>
            <link>https://medium.com/@Damien.Diehl/reified-generics-inline-functions-ae12e7f60db5?source=rss-735914bc25fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae12e7f60db5</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Damien Diehl]]></dc:creator>
            <pubDate>Fri, 02 Nov 2018 15:01:01 GMT</pubDate>
            <atom:updated>2018-11-03T23:12:08.192Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reified Generics &amp; Inline Functions in Kotlin</h3><p>One of my favorite features in the Kotlin programming language is <a href="https://kotlinlang.org/docs/reference/inline-functions.html">reified generic types</a>. Reified generics allow us to write generic functions in a way that is simply not possible in Java. In this post, I want to introduce you to the idea of reified generic types, and explain why they are useful. Then I will show some practical examples of how we can use them to write idiomatic Kotlin functions for common situations in Android development.</p><h3>Type erasure in Java</h3><p>Android system services are useful for accessing a variety of APIs, such as NotificationManager for creating notifications, or ConnectivityManager for getting information about network state. All new Android developers learn how to access a system service early on in their training. The code looks like this:</p><pre>NotificationManager manager =<br>    getSystemService(NotificationManager.class);</pre><p>A new Java developer might wonder, why do we have to pass a class instance as an argument to the getSystemService function, if we already specified the type of the variable? Can’t the compiler infer the type we want? Let’s try to write a generic function to retrieve a system service, and see what happens.</p><pre>public &lt;T&gt; T getSystemService() {<br>    return getSystemService(T.class);<br>}<br>NotificationManager notificationManager = getSystemService();</pre><p>Great, that should work! Wait a second, this doesn’t compile.</p><pre>&gt; Task :app:compileDebugJavaWithJavac<br>MyActivity.java:26: error: cannot select from a type variable<br>        return getSystemService(T.class);<br>                                 ^</pre><p>This is because generic types are entirely <a href="https://www.wikipedia.org/wiki/Compile_time"><em>compile-time</em></a><em> constructs</em>. The Java compiler uses these types to ensure we can’t, for instance, add an Integer into a list of Strings. At runtime, however, these types are <a href="https://en.wikipedia.org/wiki/Type_erasure">erased</a>. This means our calls to getSystemService would actually carry no type information with which to resolve the instance of Class. How unfortunate.</p><p>By now it should be clear why so many Java APIs take a Class instance as a parameter. The Class instance provides us the type information we need at runtime to perform logic in a pseudo-generic way. But wouldn’t it be nice if we could avoid referencing a program construct like Class, while still being able to use a generic function? With Kotlin, we can, and it’s all thanks to a feature called <a href="https://kotlinlang.org/docs/reference/inline-functions.html">inline functions</a>.</p><h3>Inline functions &amp; Reified generic types</h3><p>When Kotlin functions are marked as inline, it’s as if the body of the function is copied directly to each call site. This has powerful implications for generic functions. Because the compiler is now creating copies of the inline function, it can substitute the type argument used at each call site into the function itself. This is called <a href="https://en.wikipedia.org/wiki/Reification_(computer_science)">type reification</a>, and requires us to also mark the generic type parameter as reified.</p><p>Using both reified generic types and inline functions, we can now write a function that satisfies our earlier quest to write a generic function that avoids references to program constructs such as Class.</p><pre>inline fun &lt;reified T&gt; Context.getSystemService(): T = <br>    getSystemService(T::class.java)</pre><pre>// both compile fine!<br>val manager1: NotificationManager = getSystemService()<br>val manager2 = getSystemService&lt;NotificationManager&gt;()</pre><p>One of the goals of the <a href="https://github.com/android/android-ktx">android-ktx library</a> is to provide idiomatic Kotlin extensions on top of the standard Android APIs. The authors have used the power of reified generic types and inline functions, to provide <a href="https://github.com/aosp-mirror/platform_frameworks_support/blob/c0aeb69840772f42b98ef8abe1495f1513de5d9b/core/ktx/src/main/java/androidx/core/content/Context.kt#L25-L35">functions</a> similar to the getSystemService function written in this post.</p><h3>More examples</h3><p>Now that we have a new hammer, let’s find some nails. Any APIs that use an instance of Class as a parameter are potential candidates for a generic function.</p><p>If we want to eliminate some boilerplate when launching Activities, we can combine inline generic functions with lambda function parameters.</p><pre>inline fun &lt;reified T&gt; Context.startActivity(apply: Intent.() -&gt; Unit) {<br>    val intent = Intent(this, T::class.java)<br>    apply(intent)<br>    startActivity(intent)<br>}<br>startActivity&lt;MyActivity&gt; {<br>    putExtra(“answer”, 42)<br>    putExtra(“isCorrect”, true)<br>}</pre><p>Mockito is a popular testing library used for Android/Java development that allows us to generate mock objects with a simple call to mock(Class&lt;T&gt;). To circumvent the need to provide a Class instance, we can write an inline function with a reified generic type.</p><pre>inline fun &lt;reified T&gt; mock(): T = Mockito.mock(T::class.java)</pre><pre>val mock1: Foo = mock(Foo::class.java) // without generic function<br>val mock2: Foo = mock()                // with generic function</pre><p>For more examples of using functions with reified generic types, check out APIs provided by the <a href="https://github.com/aosp-mirror/platform_frameworks_support/tree/androidx-master-dev/core/ktx">Android-KTX library</a>.</p><h3>TL;DR</h3><p>In summary, inline functions and reified generic types allow us to write generic functions that use information provided by the generic type argument at its call sites. This is possible because unlike with non-inline functions, the compiler is able to inline the type information required at runtime at each call site. This is particularly useful when interfacing with APIs that require instances of a Java Class.</p><p>Hopefully this post has explained how reified generic types work, and shown how you can use them in your own projects to write idiomatic Kotlin, and less redundant code. Any questions or feedback are more than welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae12e7f60db5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparison Shopping: Searching for JavaScript Engines for Android]]></title>
            <link>https://medium.com/tech-quizlet/comparison-shopping-searching-for-javascript-engines-for-android-bdc656538f2e?source=rss-735914bc25fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdc656538f2e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[android-libraries]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Damien Diehl]]></dc:creator>
            <pubDate>Tue, 13 Dec 2016 18:44:57 GMT</pubDate>
            <atom:updated>2018-03-06T19:50:09.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNxZsBpcXQyaFCpffiNOKQ.png" /></figure><p>When your product spans web, iOS, and Android, sharing code between apps not only saves a lot of engineering time, but also results in user benefits: shorter iteration cycles, cross-platform availability, and consistency. Code sharing is particularly useful when your code requires constant tweaking. These iteration cycles typically involve manually translating code from one language to another, and can prove to be difficult and time-consuming.</p><p>At Quizlet we build learning tools — students and learners can create a set of flashcards and study them using a variety of games and memorization aides. The core code that determines whether a user’s answer is correct contains small details for different languages and content types. This is a great example of an area of our product where sharing code is particularly useful; we are able to iterate on the grading algorithm in one place, then ship to all of our apps simultaneously.</p><p>A common way to share code between platforms is to use an interpreted language such as JavaScript. For companies developing mobile apps to complement their website, the code may already exist on one platform. However, using JavaScript code on platforms that use compiled languages natively, such as iOS and Android, can be troublesome. iOS developers have an easier time on this front: Starting from iOS 7, Apple includes the JavaScriptCore engine with the operating system, as well as bindings for Objective C.</p><p>Android, on the other hand, does not have such an engine included. Fortunately there are a few open-source projects that attempt to solve the problem of interpreting JavaScript code in Java and Android applications. The integration for each solution is not completely straightforward, and the performance of each has not been thoroughly documented from any source we could find.</p><p>After investigating several of these solutions, we have found one that provides acceptable performance and device compatibility to enable us to use JavaScript on Android. First we will discuss our testing procedure used for each of the libraries we have investigated, then dive into the tradeoffs of using each library on Android. Finally, we will discuss our experience with using shared JavaScript in the Quizlet Android app in production.</p><p><em>Edit 12/16: Due to feedback from several readers wondering about Duktape, we looked into the library and updated this post with our findings. All tests were completely re-run to ensure consistency.</em></p><h3>Libraries</h3><p>We found and evaluated four promising libraries:</p><ol><li><a href="https://github.com/evgenyneu/js-evaluator-for-android">JS Evaluator for Android</a>, based around the native Android WebView.</li><li><a href="https://github.com/ericwlange/AndroidJSCore">AndroidJSCore</a>, a Java wrapper around the WebKit JavaScriptCore engine.</li><li><a href="https://github.com/eclipsesource/J2V8">J2V8</a>, a Java wrapper around Google’s V8 JavaScript engine.</li><li><a href="https://github.com/square/duktape-android">Duktape Android</a>, the Duktape embeddable JavaScript engine packaged for Android.</li></ol><p><a href="https://github.com/mozilla/rhino">Rhino</a> was also previously evaluated as a potential solution, but at the time we found it was not performant enough to be usable in the Android context.</p><h3>Test Procedure</h3><p>To evaluate the performance of each solution, we wanted to account for several factors, including speed of marshaling JavaScript into the engine, speed of execution for simple scripts, and the initialization time for the core objects used with each engine.</p><p>We set up a simple test app that has a few modules. Each module lets the user select an engine to use for the test, and enter a number of iterations to be executed serially, allowing them to stress test each engine in various scenarios. The app tracks the cumulative execution time for each iteration, and displays it to the user once all iterations have completed.</p><p>The test modules are as follows:</p><ol><li><em>Initialization</em>: Creates the JS context objects for each engine in a loop, and optionally shuts them down, if the library includes a mechanism for doing so.</li><li><em>Looping</em>: Executes a loop in JavaScript that performs a simple string comparison in each iteration.</li><li><em>Loading</em>: Marshals a 174 KB array of sample JSON data into the engine.</li><li><em>Grading</em>: Executes the JavaScript code used for grading answers in two of Quizlet’s core study modes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4IvE3DfCdSr-Lgl9IUNTg.png" /><figcaption>JavaScript performance testing app</figcaption></figure><p>There may be more considerations for other projects utilizing shared JavaScript, but in our case, this harness allows us to effectively evaluate performance. The tests executed for this analysis were performed on a Google Pixel XL running Android 7.1.1.</p><p>On top of the runtime considerations covered in the tests above, we also needed to consider the increase in APK size resulting from including each library in the app, and the reliability of each library when attempting to run shared code on various Android devices.</p><p>Code for the test app can be found on <a href="https://github.com/quizlet/android-javascript-performance-testing">GitHub</a>.</p><h3>JS Evaluator for Android</h3><p>The advantages of JS Evaluator are immediately clear. No additional native binaries are required — the library simply uses the native Android <a href="https://developer.android.com/reference/android/webkit/WebView.html">WebView</a> class to execute JavaScript and return it to the user. This makes adding the dependency very easy for developers, and also means the APK size increase is very minimal. Including the v1.0.7 dependency in our test project resulted in only a 10 KB increase in size of the debug APK (without ProGuard). The library can be imported as a gradle dependency, using <a href="http://jitpack.io/">JitPack</a> as a repository source. Instructions in the README are fairly straightforward.</p><p>For performance, we found JS Evaluator to be fairly limited. The author states that the library is not designed to handle large amounts (~1 MB) of JavaScript. We found this was fairly accurate: The library was not able to load our 174 KB test data file for more than a few iterations of the loading or grading tests. Average initialization time was 28 ms, which was fairly fast compared to J2V8.</p><p>Code execution was a bit slower than with AndroidJSCore and J2V8, clocking in around 20 ms per iteration in the looping test, and 103 ms per iteration in the grading test. A critical limitation of this library worth mentioning, is that every call to JsEvaluator.evaluate() spawns a <em>separate JS context, </em>meaning all code required for execution must be passed in every call. This is different from AndroidJSCore and J2V8, where objects and functions assigned in a JS context can be re-used in subsequent calls. Users requiring a large amount of JS in context may see decreased performance, as they need to concatenate all of the JS into a single string, then marshal it into the engine every time they want to execute the code.</p><h3>AndroidJSCore</h3><p>AndroidJSCore is an appealing library because it is a wrapper around Webkit’s JavaScriptCore library, similar to the JavaScriptCore Objective C framework included in iOS 7 and above. iOS engineers at Quizlet use the framework to execute grading logic in our iOS app, so the underlying engine is one that has already proven itself in our production code. For Android, we needed to evaluate the AndroidJSCore library to ensure the same level of reliability and performance JavaScriptCore provides for iOS.</p><p>Importing the library is just as easy as JS Evaluator — simply import Maven dependency via gradle. The first thing you will notice after importing the dependency, however, is that the APK size increase is <strong>massive</strong>. AndroidJSCore includes binaries for many CPU ABIs, specifically arm64-v8a, armeabi, armeabi-v7a, mips, mips64, x86, and x86_64. For our test app, AndroidJSCore added 40.4 MB to the APK without ProGuard.</p><p>That said, it is fairly easy to alleviate this increase in APK size by using a feature of the Android gradle plugin called <a href="https://developer.android.com/studio/build/configure-apk-splits.html">APK splits</a>. With this build option configured, gradle will provide multiple versions of your APK, along with a fallback universal APK, to upload to Google Play. Using APK splits, the size increase is reduced to between 5.3 MB (armeabi-v7a) and 6.4 MB (x86_64). That’s still a large size increase to include with an app for the purpose of evaluating JavaScript code, but it is much more tolerable compared to the 40.4 MB increase in the universal APK.</p><p>Looking at performance, AndroidJSCore tested to perform better than JS Evaluator and Duktape, but slower than J2V8. It is worth noting that the performance of the library during stress tests was a bit unstable. During the initialization test, AndroidJSCore was quick to start up (around 9 ms per iteration), but after around 100 loops creating new JSContext objects, the library stopped processing further calls.</p><p>For most use cases, re-initializing the library in a loop is not a realistic scenario, so in the loading and looping tests, we only initialized JS context objects once, and re-used them for each iteration. The looping test proved most successful for AndroidJSCore, averaging 1.5 ms per iteration. The loading test failed sporadically, executing around 7 ms per iteration when successful. Similarly, the grading test averaged 5 ms per iteration, but tended to fail between 5 and 100 iterations.</p><p>As a last note, AndroidJSCore provides an API for interacting with JavaScript objects in Java, allowing users to interact with Java abstractions for JavaScript objects, functions, and other entities.</p><h3>J2V8</h3><p>J2V8 is a library that provides a set of Java bindings for V8, a JavaScript engine by Google. The project seems to be in active development and well-supported. The documentation for J2V8, however, proved to be somewhat troubling during initial integration. Despite several articles and blog posts by the author linked in the README, each source seems to reference different versions of the library, and it was difficult to find the most up-to-date setup instructions for Android. In the end, we simply imported the AAR for the latest version of the core dependency (4.5.0) found in the Maven Central archives.</p><p>Similar to AndroidJSCore, J2V8 includes pre-built binaries for the two most common CPU ABIs amongst Android devices, armeabi-v7a and x86. Because only two binaries are included for this library, the universal APK is only a 7.4 MB size increase. Using APK splits, this can be reduced to 3.5 MB for the armeabi-v7a APK, and 3.9 MB for the x86 APK.</p><p>J2V8 was very performant in our tests compared to the other libraries discussed. Despite a high initialization time of around 143 ms on our test device, the execution time was faster than both AndroidJSCore and JS Evaluator. The looping test averaged about 0.5 ms per iteration, loading averaged 2.9 ms per iteration, and grading averaged 1.9 ms per iteration. And unlike AndroidJSCore, we found the V8 engine to be very stable; executing 1000 iterations of any module in our test app completed without failure.</p><p>A noteworthy “feature” of J2V8 is its insistence on remaining single-threaded. V8 instances must be accessed on the same thread on which they were created, else the library itself will throw an error. This can prove problematic if you try to initialize the V8 engine at the start of your application using an arbitrary thread, and then use the V8 instance on a different thread. An example of working within this requirement can be found in the V8 implementations of each module in the test app.</p><h3>Duktape Android</h3><p>This library provides a solid JavaScript engine for the Android environment. It’s a library from Square, a large contributor to open-source projects for Android, and the project is well-supported. Integration is very easy, with instructions in the README for adding a simple gradle dependency.</p><p>Duktape provides native binaries for the same CPU ABIs as AndroidJSCore, and therefore should be runnable by all Android devices. And despite including the same number of binaries, this library is actually <em>a lot</em> smaller than both AndroidJSCore and J2V8, with the 1.1.0 version adding only 2.1 MB to our test APK. This size increase can be reduced to between 247 and 358 KB using APK splits — not a huge hit on app size.</p><p>The context object for Duktape initialized faster than that of any of the other libraries tested, around 3 ms per iteration. This fast initialization time can be beneficial, as it allows users to shut down instances of the context object, instead of re-using them between calls to the API, risking native memory leaks.</p><p>On the code execution side, however, Duktape ranked lower than AndroidJSCore and J2V8 in terms of marshaling and execution. Specifically, it clocked in at 58 ms/iteration in the loading test, 13 ms/iteration in the looping test, and 9 ms/iteration in the grading test. Interestingly, and possibly a point for further investigation: Duktape performed better in the grading test compared to the looping test, relative to the other libraries tested. From a reliability standpoint, Duktape held up as well as J2V8, executing thousands of iterations in each test module without issues.</p><p>In lieu of the Java representation of JS objects in AndroidJSCore and J2V8, Duktape provides a facility for calling Java code directly from JavaScript, by creating a Java interface and implementation class, and setting it as a global object in a Duktape instance.</p><h3>Test Results</h3><p>We ran each of the tests in our test app on a Google Pixel XL running Android 7.1.1. Results are in the charts below, displayed in iterations/second (higher is better).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErjOZISfm8S87Ui5In4xAQ.png" /></figure><p>It’s worth restating that JS Evaluator and AndroidJSCore were relatively unreliable in testing. The numbers above are averages over as many iterations as each library could handle before throwing an error or crashing. For J2V8 and Duktape, each test was able to run for 1000 iterations or more, and did not exhibit errors.</p><p>Here’s a summary of our findings for each library tested:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*Ge7yaFiQQDcCfWfvQ4w86A.png" /></figure><h3>Use in Production</h3><p>Given the speed and reliability of code execution, we decided to try J2V8 as the shared JavaScript solution for the Quizlet app.</p><p>Our prior implementation of the grading logic was a simplistic translation of the JavaScript used in Web and iOS. To mitigate the risk of certain end user devices being unable to load the V8 binaries, we kept the original implementation as fallback logic, as well as added logging to determine the scope of devices experiencing issues.</p><p>Unit testing a native library also proved to be somewhat of an issue, as the binaries included with J2V8 were not loadable on our development machines (OSX) or CI (Linux). This was solved by copying the libj2v8_macosx_x86_64.dylib and libj2v8_linux_x86_64.so files from the respective versions of the <a href="http://search.maven.org/#search%7Cga%7C1%7Cg:%22com.eclipsesource.j2v8%22">J2V8 dependencies</a> to our project’s JNI folder. After adding these files, unit tests ran on our local machines and CI as expected.</p><p>So far the results have been very positive, with no reported crashes or issues from users. We look forward to continue to use shared JavaScript in the Quizlet app to accelerate iterations on our shared code, and provide a more consistent experience for users on all platforms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdc656538f2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tech-quizlet/comparison-shopping-searching-for-javascript-engines-for-android-bdc656538f2e">Comparison Shopping: Searching for JavaScript Engines for Android</a> was originally published in <a href="https://medium.com/tech-quizlet">Tech @ Quizlet</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>