UI Roundup 2017: Polymer

Two years ago, Polymer looked like an equal competitor to AngularJS. At the time, it wasn’t clear which one would win the race. Truth to tell, it’s not clear today. The JavaScript world is incredibly volatile and capricious. But the numbers I collected clearly indicate Angular (nowadays without JS) is much more important. At the same time, they indicate that Polymer is here to stay.

Continue reading

Angular Takes the Sting out of Writing Components

It’s astonishing how simple writing web components is with Angular. In a way, this shouldn’t be a surprise: components are the building blocks of every Angular application. However, last week we wrote a component I already knew to be difficult to implement in merely an hour or two. That was really a surprise.

Our choice was a multi-choice select box. There are plenty finished components out there. However, Angular 2+ is still young, so there are few (if any) native Angular multiple-choice boxes we can use. Integrating a component based on other technologies like jQuery is possible, but usually, it takes some time and it’s always a compromise. So I reluctantly agreed when my co-worker suggested to quickly write our own component. “It’s simple”, he said. “It ain’t much work”. It’s true. It wasn’t.

Key to success: template language

The key to success is the clever template language of Angular. More often than not, I’m unhappy with template languages because they always feel clumsy. Angular’s template language doesn’t. Of course, that’s simple because it doesn’t aim to be a general-purpose language. It’s been written specifically for a single purpose, and it serves this purpose well.

I don’t have the source code at hand, so let me sketch our source code from memory. The multiple-choice combobox consists of an input field, which is always visible, and a pane containing the options. The pane is hidden most of the time. So the HTML code (or rather: pseudocode) looks like so:

<input [(ngModel)]="selectedValues" 
       (onfocus)="optionsVisible=true"
       (onblur)="optionsVisible=false">
<div [attrs.visible]="optionsVisible">
  <div class="checkbox" *ngFor="let option in options">
    <label>
      <input type="checkbox" [(ngModel)]="option.selected"
             onchange="updateResult()"> 
      {{option.value}}
    </label>
  </div>
</div>

This little snippet reads and writes like plain vanilla code. But in reality, it’s revolutionary. It takes a lot more code in Java to write an equivalent JSF component. I also compared this code to my AngularPrime/Dart framework I wrote a couple of years ago. Dart is a fine language, but it took much more time and effort to write a simple component.

The component class

Of course, the HTML code is useless without the TypeScript glue code. But again, this code is fairly straight-forward. The sketchy pseudocode looks like this:

export class Option {
  label: string
  selected: boolean = false
}

@Component({
  selector: "multiple-choice",
  templateUrl: "multple-choice.html"})
export class MultipleChoice {
  @Input() options: Options[]

  @Output() result = new EventEmitter(string)

  optionsVisible: boolean = false

  updateResult(): void {
    let result = options.filter(option => option.selected).
             reduce((option, previous) => previous + "," + option.label, "")
    result.emit(result)
  }
}

Another key to success: @Input and @Output

We’re almost there! All we need to add is a little CSS file to arrange the panel properly below the input field. Everything else is handled by Angular: we can pass the list of options to the component using the @Input decorator, and @Output sends the result to the outer component:

<multiple-choice [options]="colors" 
                 (result)="setSelectedColors($event)">
</multiple-choice>

Wrapping it up

Of course, I’ve omitted some details to keep things simple, and I’ve shown only pseudocode. But even the real source code is surprisingly simple. Angular focuses on writing components. Therefore, it makes writing components as simple as possible without sacrificing power. I had the opportunity to compare different approaches, and I’m astonished by the ease of use of Angular.

Newsflash: Saving HTML Pages or Snippets as an Image

There’s a nice JavaScript project allowing you to save HTML snippets as an image. I didn’t test it yet, but the Fiddles look nice (for instance, this one).

Basically, the library traverses the DOM, using an HTML5 canvas to draw the elements it finds. In other words, it’s an HTLM rendering engine written in JavaScript. Most likely, that means that the library only supports a small fraction of the giant set of HTML attributes and elements. But still, it seems to support many common use cases.

Another approach is putting foreign objects into an SVG and to draw that SVG image into an HTML5 canvas. The foreignObject is currently only partially supported by most browsers, but even so it seems to do the trick for many common usecases.

The Dark Path?

It always pays to listen to Uncle Bob Martin. He’s clearly someone who’s got something to say. But that doesn’t mean I always agree. Today, I don’t. And I consider it interesting why we disagree.

I’ve just read Robert Martin’s post“The Dark Path”. He picks three innovative traits of Kotlin and Swift: strict null checks, strict exception handling and making classes final (in Java speech) or closed (in Kotlin lingo) by default. It’s an interesting post I recommend to read. Uncle Bob shortly explains these features, continues with complaining about languages becoming too complex because they try to fill each leak of their predecessor languages, and closes with an ardent call to write tests. Like usual, he arguments very convincingly. It’s hard to disagree after reading the article. Yet I do.
Continue reading

How to Use a JavaScript DataTable in an Angular Application

Fork me on GitHubThere are several data table widgets for Angular, but none of them matched our project’s needs. I’m sure that’s simply a matter of time. Angular2 is young, and the third-party libraries are even younger. They simply didn’t have enough time to accumulate features and maturity. So why don’t we use one of the seasoned JavaScript data tables?

As it turns out, Louis Lin had the same idea creating the Angular DataTables project. It looks promising, but at the time of writing, it was only 26 days old. So the feature list is pretty short. When you’re reading this article, things have probably improved. However, today I don’t want to tell you how to use a third-party data table. Instead, I’ll tell you how to do it yourself. Before we start to wallow in the source code, let’s start with what developers usually do: a short market survey. If you’re in a hurry, skip that section or jump directly to the source code of the demo on GitHub.
Continue reading

Charts with Angular: ngx-charts (Formerly: ng2d3)

Originally, I wanted to write an article about ng2d3. That’s a fine library bringing the power of D3.js charts to the Angular2 world without the price. D3 requires you to adopt a special programming style. You have to learn and use a new programming paradigm, the data-driven programming style. ng2d3 doesn’t require such a thing. You just pass it the data, and it’ll draw the diagram for you.

The only problem with ng2d3 is that it doesn’t exist anymore. More precisely, when I started writing, the team published a new major version (including a couple of breaking changes) and changed the name of the project. Now it’s called ngx-charts. In the view of the new semantic versioning strategy of Angular, the name makes a lot of sense. Calling a framework “ng2-something” won’t work when Angular4 will have been published, skipping Angular3 altogether.
Continue reading

How to Use BootsFaces and PrimeFaces in the Same Project

I’ve always promoted BootsFaces as a companion framework for PrimeFaces, but many developers report it’s difficult, if not impossible, to combine these two frameworks. Things are particularly nasty if you’ve already got a (possibly huge) PrimeFaces application. Some developers report that even adding a single BootsFaces component will distort your application’s layout. So I’ve decided to examine the problem more closely and to do something about it. This article sketches how to integrate BootsFaces components into a PrimeFaces application. I’ve also created a project at GitHub demonstrating the idea. Note that this article doesn’t show how to use a PrimeFaces component in a BootsFaces application. Of course, that’s almost the same problem, but the source codes below only consider the first use case.
Continue reading

What’s New in BootsFaces 1.0?

BootsFaces 1.0 has been released. Actually, we’ve already published the first bugfix release, BootsFaces 1.0.1. I was a bit shy to proudly announce the 1.0.0 version because we had so many obstacles to overcome. Apart from the usual obstacles like exhausting projects at work (and they were exhausting this time!), there were also the earthquakes in Italy, which kept at least one of our team members busy, although they didn’t suffer any physical harm.

Be that as it may, BootsFaces 1.0 (and 1.0.1 in particular) is a great step to maturity. It’s the first version we officially call “production-ready”. Truth to tell, we were always convinced you can safely use BootsFaces in production. But most versions we’ve published in the past focused on features. This time we tried to focus on stability instead of new features when we prepared the 1.0 version. I counted 26 bugfixes that were important enough to open a bug ticket. Plus, almost twenty minor enhancements and three new components. However, we also added one or two major improvements, such as adding support for both horizontal and inline forms.

Download coordinates

Before starting the long list of details, let me provide you with the download coordinates:

Add these lines to your project’s pom.xml:

<dependency>
    <groupId>net.bootsfaces</groupId>
    <artifactId>bootsfaces</artifactId>
    <version>1.0.1</version>
    <scope>compile</scope>
</dependency>

Add this line to your project’s .gradle build file:

compile 'net.bootsfaces:bootsfaces:1.0.1'

The BootsFaces project comes with both a Gradle build file and a Maven build file. The Maven pom.xml is the easy way to get started and should suffice for most purposes. Only if you want to tweak and optimize BootsFaces, you need the Gradle build. In particular, the Maven build doesn’t generate the CSS and JS files itself, but relies on the output of the Gradle build. By the way, that’s the reason why we keep the generated file in GitHub.

In any case, the URL of the repository is https://github.com/TheCoder4eu/BootsFaces-OSP.

Update Dec 27, 2016: Bugs

During the last couple of days, we’ve found and fixed a couple of bugs. If you happen to run into a bug, check our bug tracker if we’ve already solved the bug, and check out the sneak preview version of BootsFaces 1.1.0-SNAPSHOT. Strictly speaking, this version is not intended to use productively. Use at own risk. Of course, BootsFaces is published under an Apache V2 license, so every version of BootsFaces is published on an “as-is” basis, without any warranties. The difference between the snapshot and the final version is that we’ve tested the final version more intensively.

Continue reading

How to Connect HTML Elements With an Arrow Using SVG

The other day, had a list of items on the left-hand side, and another list of items on the right-hand side. Some of these items are connected, some of them are not. Wouldn’t it be nice to show this by connecting the item with an arrow?

At first, there’s nothing new here. We’ve been drawing and connecting boxes, circles and arbitrary shapes in the IT business for ages. Just think of flow charts or organigrams. There’s even a nice PrimeFaces component for that.

The problem is that my application was an Angular2 application, not a JSF application. Plus, the PrimeFaces component, which is really nice, didn’t match my requirements. I didn’t want to display a flow chart. The boxes I wanted to connect contain live data and even images. So the task is to connect arbitrary <div /> elements with an arrow.

At first, the task seems a bit intimidating, but once I’ve started to delve into it, it became surprisingly simple. Simple enough I can even provide the source code at the end of the post.
Continue reading

Electron Brings JavaScript to the Desktop

Let’s continue my “Java on the desktop” series with something that’s not Java, but interesting nonetheless. Electron is a framework wrapping your HTML5 application in a native window of your operation system. Other than most projects in the JavaScript universe, Electron does not follow a “mobile first” approach. Quite the contrary, it’s fairly opinionated in that it supports only three platforms: Windows, OSX, and Linux. This includes access to your computers file system and access to the Windows registry via third-party NPM modules. If I’ve got it right, it even allows you to install your application as a Windows service, which is kind of scary. You know, not too long ago every security expert recommended deactivating JavaScript in the browser because of alleged security risks. Obviously, we’ve come a long way.
Continue reading

How to Wrap BootsFaces (or JSF in General) as a Native Desktop Application

When I showed the draft of my last post (the “Java on the Desktop” survey article), my friends surprised me by saying that nowadays desktop applications are sort of exotic. Everybody’s doing mobile or at least web applications. But the good old desktop has fallen into oblivion. That’s pretty strange, given that most of us do most of their daily work at desktop PCs or decent-sized laptops.
Continue reading

Java on the Desktop

For some reason, the vast majority of developers has accepted the browser as the operation system for their applications. While there are some good reasons for this, I never really bought into it. HTML5 has eliminated most of the pain point of web applications, but I still insist that most customers don’t really want to use a web application. We’ve taught them to accept to open the browser to do their daily work, but there are still quite a few disadvantages to this approach. The “old stagers” among you know how many obstacles we had to overcome before the browser became a really useful operation system for writing applications. Just for the fun of it, let’s start this article summarizing some of them:

  • How to deal with the “back” and “forward” buttons in a web application?
  • How to print a document from a web application? Most developers export documents to be printed as PDF files, but wouldn’t it be nice to be able to print documents without this detour?
  • How to import an Excel file into your application?
  • More generally speaking, web applications run in a sandbox preventing access to low-level resources such as your computer’s file system.

Continue reading

Angular2 Component Libraries

A good third-party component library can give your application development team a boost. This article collects a list of popular UI component libraries for Angular2. It goes without saying that this list can never be complete, so it’s probably going to change and expand over time. If you know of a useful Angular2 widget library, don’t hesitate to leave a comment so I can complete the list.

By the way, this list is just that: a list. I’m adding a short introduction to each library, but it’s not the same as a review. I’ll postpone that to follow-up articles. If you like or dislike on of the library, I’d like to hear from you, especially if you also add a short explanation.

General purpose widget libraries

  • Ionic was already a well-known UI framework in the AngularJS 1.x age. There’s also an Angular2 port. Ionic comes with a CLI tool which simplifies getting started. It also provides its unique layout which blends in nicely with the look and feel of many current mobile devices. There’S a nice tutorial at scotch.io.
  • PrimeNG is an offspring of the well-known PrimeFaces JSF library. It’s an open source project hosted at GitHub. At the time of writing (Oct 07, 2016) I counted some 70 components, providing enough widgets for writing an enterprise application. Like PrimeFaces, PrimeNG is a commercial library. In this particular case, this means you can get the library itself for free, but you can order a support plan. There’s a PrimeNG PRO with commercial support and premium templates like Ultima NG. For some reason, the team didn’t make their pricing public yet, but they told me they already have a couple of very big customers. Judging from the list they showed me I daresay to call PrimeNG a great framework even if I haven’t used it myself.
  • ng2-bootstrap is a component library that combines the grid system and the theming of Bootstrap with Angular2. At the time of writing (Oct 07, 2016) it supports 15 components and both Bootstrap 3 and Bootstrap 4. 15 components doesn’t sound much, but the tool box contains most components you need. A co-worker of mine uses it for their current project and reports that they a happy with it.

Widget libraries providing individual components

Talking of data tables: PrimeNG has a fairly powerful data table. I didn’t compare it to the other data tables in this list, but I think they all play in the same league.

Commercial widget libraries

Since I don’t want to spend money on commercial libraries just to test them, let’s suffice to mention these libraries.

  • KendoUI is the Angular2 offspring of the well-known KendoUI library. So it’s not surprising that it looks fairly complete. Prices start at 999$ per developer license.
  • Wijmo 5 is also a library with a long history. Hence the Angular2 offspring also seems to offer almost everything you need. Prices start at 695$ per license.

Is Java Going to Become Invisible?

In a sense, Java has vanished from the client many years ago. With the exception of Android, the vast majority of Java runs on a server in a data center. From the average user’s perspective, Java has become invisible. When we talk about Java UI programming, most people think of Spring MVC, JSF and Ozark.

I’m still trying to make sense of the new Java EE 8 plans Oracle revealed at JavaOne a couple of weeks ago. My first impression was that the new focus on cloud computing means that Java is going to molt again. The Java EE 8 roadmap proposal indicates just that.
Continue reading

The Rise and Fall of Scala

There seems to be a consensus in the Java community that the Scala programming language is already on the decline. I consider this a pity because I always enjoyed programming in Scala. Actually, I even started this blog to support alternative JVM languages like Scala. But the market has decided differently. Moshe Kranc has written an excellent analysis about the rise and fall of Scala. I found Moshe’s article interesting enough to summarize it and to add a couple of thoughts of mine.

Before I start

However, I’ve also read some of the 169 comments to Moshe’s article, so I’d like to add a few words. First of all, I’m really fond of the Scala language. I’m not trying to write an anti-Scala article. Quite the contrary. I’m following the fate of Groovy and Scala for at least ten years now, and I’m still puzzled why the industry doesn’t adopt one of these languages. In many aspects, both languages are clearly superior to Java.
Continue reading

Newsflash: JavaEE 8 Road Map Proposal

This newsflash is a true “flash”, currently consisting only of a single link to the current proposal of the JavaEE 8 road map:

Proposal of the JavaEE 8 road map as of September 19, 2016

However, if time allows, I’ll either add to this newsflash later or write blog entries covering certain aspects of the shift of the plans. Stay tuned!

UI Roundup 2016: Microsoft UWP and Xamarin

No comprehensive survey about UIs can ever be complete without covering the Microsoft world. Java and JavaScript may be all good and well, but sometimes you need more control over your hardware. Both languages run in a sandbox trying to abstract from the hardware the application is running on. Most of the time you won’t notice, but there’s a major performance penalty, and you can’t access low-level resources. So let’s have a look at what Microsoft has in store for you. Traditionally, the particular advantage of using native Windows programming is the seamless integration with the operating system and – to a lesser extent – with the hardware.

So let’s have a look at Microsoft’s UWP platform and at Xamarin, a framework they’ve acquired in February 2016.

Kudos to my co-author

But before that, I’d like to introduce you to my co-author, Janis Saritzoglou. This article wouldn’t have been possible without him. Janis wrote his bachelor thesis about UWP and dedicated an afternoon to explain UWP and Xamarin to me. He also proofread this article and added a couple of interesting insights.

That said, let’s continue with UWP.
Continue reading

HTML5: Optional HTML Tags

The other day Marco Rinck tweeted something that’s very confusing, almost disturbing. Google’s HTML style guide suggests to omit optional HTML tags. Taking in mind that the page rank of your website is influenced (among other things) by whether your page has a clear layout and a good coding quality, following these guidelines is almost mandatory. Granted, I didn’t check whether this particular style guide is linked to the results shown in the webmaster tools, but you get the idea: if Google publishes a style guide on HTML and CSS, it’s going to have an impact on the market. So let’s have a close look at it.

What are optional HTML tags?

At first glance, the idea of declaring certain HTML tags “optional” and suggesting to omit them makes a lot of sense. Putting it in a nutshell, the idea is to make the code more human-readable. More to the point, the suggestion is to write HTML code the way the average human would write it if they didn’t happen to be a developer. Developers have learned to love clear structures, but that’s not the way most people think. A particularly fascinating property of the human mind is its ability to recognize patterns. Even better, it’s able to infer patterns where there are none.

Basically, that’s the idea of optional HTML tags: you don’t have to write an HTML tag if you can easily infer it from the context.

For instance, there’s no point in writing the <html> tag. The document is shown in the browser, so we already know it’s an HTML document. Similarly, there’s no point in wrapping the <head> tag around the <title> tag, and the <body> around the <for> or <p> tag. Both forms and paragraphs make only sense in the body of an HTML document, so it’s easy to infer the <body> tag.

Cool! But…

Being a human being – and a particularly lazy one – Google’s style guide fills my heart with joy. Mind you: having to end each and every paragraph with a </p> tag before starting a new paragraph is really silly. Actually, it’s the number one mistake when I add a new page to our BootsFaces showcase.

On the other hand, the new style guide is exactly the opposite of what web designers have been taught during the last couple of years. I’m not entirely sure about the version numbers, but as far as I remember, starting with HTML4, XHTML was promoted as the new way to go. Former versions of HTML – or rather, the browser rendering engines – tended to be very sloppy. Or, putting it positively, they mapped the pattern inference capabilities of the human brain. The (then) new standard was to get rid of inference. The idea was to define everything in a clear, concise manner.

What about parsers?

I don’t know why this clean coding style was propagated, but my theory (hey, that’s pattern inference at it’s best!) is that the idea was to make HTML machine-readable. Clean XHTML code can be parsed by an XML parser. In fact, that was what allowed me to write BabbageFaces. JSF usually generates very clean XML code which can be read and analyzed by an XML parser. That’s what I did to reduce the size of the HTML code sent to the browser.

However, I consider BabbageFaces a nice but failed project, basically because hardly any JSF page fulfills the strict requirements of XML. The average JSF page renders code that can almost, but not quite be read by an XML parser. Almost always optional HTML tags are used. Browser vendors always knew that HTML pages are written by human beings, so they introduced pattern inference from day one. So browsers don’t have trouble displaying the HTML code generated by JSF pages. The XML parser of BabbageFaces quickly ran into trouble with the same pages. Which is sort of remarkable, given that the HTML code generated by JSF frameworks usually is a lot cleaner than HTML code written by humans.

We need new parsers!

Far be it from me to resist the new guidelines. Quite the contrary. In recent years, compiler manufacturers have learned a lot. The semicolon that’s required at the end of each Java statement originally was introduced to make it easier to implement parsers analyzing the source code. It took compiler manufacturers a couple of years to recognize that the semicolon can be induced from context.

There are many programs out there analyzing HTML code. I don’t know whether they cope with tag inference or not. Thing is, HTML4 made it official that they don’t have to, while HTML5 officially makes tag inference part of the HTML language. As a consequence, you can’t simply use an XML parser to parse HTML pages. You need a full-blown HTML parser. A short investigation showed that Jsoup may be such a parser, but please don’t take my word for it: neither did I try it, nor did I compare it with other parsers.

Wrapping it up

Actually, the Google HTML and CSS style guide give the best summary itself:

This approach may require a grace period to be established as a wider guideline as it’s significantly different from what web developers are typically taught.

As a human being, I welcome the new standard because it makes both reading and writing HTML pages easier. As someone who sometimes writes programs to analyze HTML pages, I’m not so sure. At least, the idea to simply use an XML parser to analyze an HTML page is doomed.


Dig deeper

HTML5 specification of optional tags
Google’s HTML styleguide on optional HTML tags

Blisk – a Browser to Make Web Programming Easier

Mobile first! Seriously? Do you really optimize your application for mobile usage?

Actually, you can’t. The current state-of-the-art makes it difficult to adopt the “mobile first!” approach seriously. Mind you: that would require you to program your application on the phone instead of using your desktop browser. Until today, I’ve seen such an approach only with iOS programming and with UWP/Xamarin. The application is developed on the desktop, but run and tested on the cell phone or the tablet.

The other day a friend of mine, Dario D´Urzo, showed me another option for web developers. What started as a small JavaScript plugin two years ago has evolved to a full-blown browser in 2016. More precisely, it’s a browser based on Chromium which adds a number of tools dedicated to web designers and web programmers.

Targeting multiple devices

When you open a URL in Blisk you’ll see the web page twice. On the right-hand side, there’s the desktop view you expect. On the left-hand side, you see the same page in a simulated smartphone. As you can see in the screenshot, both views are remarkably different. It’s great to be able to seem both views at a glance. This enables you to truly adopt the “mobile first!” slogan. Even better: if you scroll one of the windows, the other windows scrolls simultaneously. Thus you can compare both the look and the feel of both displays.

Blisk supports a number of devices out of the box. It doesn’t cover every smartphone and every tablet available on the market, but the number of devices seems to cover almost every use case.

Multiple inspect views

Seeing multiple devices at a glance is just a start. You can also open device-specific developer tools and keep them open simultaneously. That, in turn, allows you to find differences between devices a lot faster than with the traditional single window.

Limitations

Being a browser based on Chromium, I’m pretty sure Blisk has an annoying limitation: it doesn’t simulate the device completely. It only modifies the screen estate the replaces the mouse pointer by a large finger touch point. What it does not do is to simulate the rendering engine. If there’s an incompatibility because – say – Safari implements a feature differently than Chrome does, you’ll still miss it with Blisk. You still need to test your application with the real device.

Automatic reload

That’s another feature I’m told to be very useful. You can configure Blisk to watch certain files or folders. When you edit and save a file, Blisk automatically reloads the page. I suspect that’s one of the features that are useful to some and annoying to others, so probably it’s good news you can also switch it off. However, if your application supports reloading, I imagine that’s a tool boosting productivity.

Code analysis

Currently, that’s only a promise. The module providing static code analysis is still under development. I’m looking forward to it. Integrating code analysis into your browser (i.e. your runtime environment) might make you aware of problems much earlier than with traditional approaches such as SonarQube.

Screen shots

Another feature that’s still under development. However, I doubt that’s a killer feature to me. Tools like Greenshot integrate so nicely into my PC I never considered taking screenshots awkward. So I’m curious – maybe the developers have a clever idea I missed?

Integration with other tools

That’s something offering more potential to boost productivity. Blisk offers to provide integration with third-party tools, such as bug trackers and project management tools. Unfortunately, this is another module still under development.

Licence

Blisk has a long licence agreement, but basically it’s free both for commercial use and for personal use as long as you don’t modify it.

Wrapping it up

As long as you are aware on the limitations, Blisk is a great tool for every web designer and web developer targeting multiple devices. At the time of writing, many interesting features are still missing. However, what’s already there looks interesting enough to adopt Blick for development.


Dig deeper

Blick project page
Blick license agreement

Newsflash: Sometimes Using Float is Faster Than Using Int in Java

Performance considerations in the eighties

Time and again, I’m surprised by the performance of modern CPUs. Actually, the speed boost astonishing me most took place a decade ago, give or take a few years. Before that, floating point operations were a lot slower than integer operations. When I learned my first assembly language, the 6502 processor was state of the art. This processor was so simple that you had to write a program to implement the integer multiplication. Multiplying floating point numbers was an even longer program. I’ve forgotten the actual numbers, but as a rule of thumb, multiplying integers was ten times slower than adding two integers, and multiplying floating point numbers was another magnitude slower.

… compared to 2016

Nowadays, x86 CPU multiply four floating point numbers in a single CPU cycle (under optimal conditions). In theory, the fastest possible operation takes one CPU cycle, to it boils down to saying that multiplying floating point numbers is every bit as fast as adding integers. The complexity of the algorithm hasn’t gone away, so this is absolutely stunning. Not only have hardware designers managed to implement the complex algorithm in hardware, they also managed to implement it in a fashion resembling parallel programming. I suppose the final algorithm isn’t that complicated. Actually, I’ve got an idea what it looks like. But it took hardware designers years to get there, so it’s obvious it wasn’t a low-hanging fruit.

What about Java?

As Grey Panther shows in his article, the effect also shows in Java programs. Under certain circumstances, integer operations can be slower than floating point operations. I don’t think that holds true for individual operations, because in this case, the latency induced by the CPU pipeline plays a major role. But when you do a lot of floating point operations, the JIT compiler and it’s optimations kicks in, allowing for an efficient CPU use. The net result is that it may pay to prefer floats over integers.

Wrapping it up

However, what’s more important, is that every data type is blazing fast. You can choose the data type that suits your problem. In earlier times, performance considerations often dictated the choice of the data type. Luckily, this is a thing of the past.

Dig deeper

Benchmarking the cost of primitive operations on the JVM
Intel® 64 and IA-32 Architectures Optimization Reference Manual