ELI5: Reactivity in Vue 3

Reactivity. It’s a popular buzzword. It’s also one of the most convenient features of front-end frameworks.
What is it exactly, and how does it work in Vue 3?

Prerequisite Knowledge

  • Basic JavaScript and JS objects
  • Basic knowledge of Vue.js

What is reactivity?

Reactivity is a programming paradigm that allows us to adjust to changes in a declarative manner.

Vue 3.x documentation

We say a value is reactive when it can update itself in response to changes in values it depends on. What do we mean by depends on? Let’s take an example.

let val1 = 2
let val2 = 3
let sum = val1 + val2

The value of sum is always determined by the values of val1 and val2, so we say that sum depends on val1 and val2.

What happens to sum when one of the values it depends on changes? In regular JavaScript, it stays the same.

console.log(sum) // 5

val1 = 3

console.log(sum) // Still 5

But if sum was reactive,

console.log(sum) // 5

val1 = 3

console.log(sum) // Sum is 6!

The value of sum would change in response to the change in a value it depended on.

What does Vue need to make a value reactive?

Vue needs to know:

  • what dependencies that value has.
  • when those dependencies change.

Vue also needs to be able to re-calculate values when their dependencies change.

How Vue knows when dependencies change

Vue wraps the data object of all components with an ES6 Proxy.
A proxy is an object that wraps a target object.

This is important because all reactive values depend (directly or not) on the properties in a component’s data object.

Proxies allow you to intercept all requests to get or set properties of the target. They also let you run any code in response to those requests.

Thanks to this, when code attempts to change one of the properties of a data object, Vue intercepts it and is aware of it.

Vue can then re-calculate any functions that depend on that value. But how does Vue know which functions depend on which values?

How Vue knows which dependencies belong to a value

To make our value reactive, we need to wrap it in a function. Using sum to illustrate again:

// we need to go from

let val1 = 2
let val2 = 3
let sum = val1 + val2

// to

const updateSum = () => 
 sum = val1 + val2

Vue then wraps all such functions with an effect. An effect is a function that takes another function as an argument. Vue then calls the effect in place of that function.

When Vue calls an effect, the effect:

  • Records that it’s running.
  • Calls the function it received as an argument.
  • Removes itself from the list of running effects after the function ends.

Remember all source values come from a Proxy (the data component)? While executing the function it wraps, the effect will need a property from the data object, and try to read it.

The Proxy will intercept that read request. Vue checks which effect is currently running. It then records that the effect depends on the property it tried to read. This is how Vue knows which values depend on which properties.

So how does Vue know when to re-run the functions that return dependent values?

The answer is once again the magic of Proxies. Proxies can intercept requests to set property values too.

Remember we now have a record of effects, as well as the values they depend on. When the value of a property in data changes, Vue needs to do one thing: check that record and update the source value.

Vue can then re-run all the effects that depend on it, and thus update the values.


This article is a simplified overview of how reactivity works in Vue 3. If you’d like to read more on the subject, here are some resources:

Source link

5 Articles every WebDev should read this week (#03)

A curated list of the top five web development must-reads from last week. Don’t miss out on the latest web development stories and insights. Read all about the cutting edge in web development, working in tech and the new tools and frameworks while learning a few new tricks.


Developers and Open Source authors now have a massive amount of services offering free tiers, but it can be hard to find them all to make informed decisions.

This is a list of software (SaaS, PaaS, IaaS, etc.) and other offerings that have free tiers for developers.


How not to learn TypeScript

“TypeScript and I are never going to be friends”. Oh wow, how often have I heard this phrase? Learning TypeScript, even in 2022, can be frustrating it seems. And for so many different reasons. People who write Java or C# and find out things are working differently than they should. Folks who have done JavaScript most of their time and are being screamed at by a compiler. Here are some mistakes I’ve seen people do when getting started with TypeScript.


Being the DRI of Your Career

At DuckDuckGo, there’s an expression: “You are the DRI of your career” (DRI: Directly Responsible Individual). I like this, both as an individual who has always felt like the DRI of my own career, and I like it as a manager because I think it makes the boundaries of what you can and can’t do for people clear.


How to Stack Elements in CSS

If you want to create fantastic and unique visual experiences on the web, you will eventually need two elements to overlap or exist in the same place. You may even just need them to be positioned near or next to each other. Let’s go over two different ways to accomplish this, one with the position property and one with CSS Grid.


The New Vue by Evan You

In this session, Evan You talks about the new Vue 3 experience: from new syntax to new docs, build tools, devtools, and TS/IDE.


Follow me on Twitter: @martinkr.

Photo by Alex Kulikov on Unsplash

Subscribe to the weekly modern frontend development newsletter

Source link

Backend Engineering Skills Are Emphasized Too Heavily for Principal Engineers

There is a bias toward backend engineers at the principal engineer level. This leaves frontend engineers heavily disadvantaged when it comes to promotion time.

When someone says they’re a fullstack engineer, what they usually mean is one of two things: 1) They’re a coding bootcamp grad that has minimal experience with Node.js and an emphasis on the frontend. Or, 2) they’re an experienced backend engineer that knows a little bit of HTML and CSS. A truly fullstack software engineer is a rare find.

That being said, principal engineer job requirements focus almost entirely on backend engineering skills. The companies I’ve worked for in the past have had requirements for expertise in areas like networking, system design, database design, building scalable microservice architecture, or designing fault-tolerant systems.

And while all those things are important, especially for someone at a principal level with a backend emphasis, these lists of requirements are often missing many skills that may be unique to frontend engineers but that are equally important.

Valuable Frontend Skills for Principal Engineers

What about the ability to build scalable design systems? Are you able to build atomic-level components that can be built up into molecules, organisms, templates, and eventually pages? Do you understand what should or should not be included in a design system’s component library? Do you understand how to provide clear design constraints to create a consistent UI while also allowing for flexibility in the usage of your components?

What about the ability to build accessible web applications? Accessibility is an often-overlooked skill but one that is becoming increasingly important, especially for software as a service companies in a competitive market. Are you able to build apps that conform to the WCAG 2.1 AA specifications? Do you understand basic design principles and common UX patterns for various widgets? What’s fascinating about accessibility is that so much of it is provided for you, right out of the box, with HTML. Yet most developers don’t create widgets that are operable using a mouse, a keyboard, and a screen reader, opting instead to focus on mouse users only and to ignore common UX patterns.

What about the ability to think clearly about microinteractions in the app? Are you able to create a seamless user experience that keeps users from becoming disoriented? Are you good at thinking through edge cases in how widgets function? Do you have a good design sense? Do you practice inclusive design? Piggybacking off of the previous paragraph, so much of accessibility is really just usability.

What about the ability to optimize performance on the frontend? Do you understand how dev, peer, and regular dependencies work? Do you understand how to optimize bundle size for your frontend app and how to avoid downloading the same resources multiple times?

Conclusion and Invitation

These kinds of skills and many more are extremely important in frontend architecture, and yet they are rarely included in skills requirements for principal engineers.

My advice to engineering leadership everywhere is to look for the valuable skills that frontend engineers bring to the table and find ways to include those skill sets in your requirements for promotions, especially for those positions at higher levels.

Source link

15 Recommended Books For Computer Science Students

We are in the modern world where the digitization of education is already going on. Now lots of blogs, articles are there on the internet to learn from. But Book has its own value, the author puts his all knowledge experience and time to write one whole book. The knowledge and details you get from a book are very precious.

In this article, I am going to discuss 15 Recommended Books For Computer Science Students

1. Clean Code: A Handbook of Agile Software Craftsmanship


Because it’s more approachable, especially for inexperienced developers, Clean Code is one of the most regularly seen books on a programmer’s desk. Clean Code focuses on tactical ideas, such as how to build classes and functions, rather than high-level procedures.

2. Head First Java


Learning a difficult new language, especially an object-oriented computer programming language like Java, is no simple undertaking. You could believe the issue is with your mind. It appears to have its own mind, one that doesn’t always want to take in the dry, technical information you’re required to learn. This book is like bible for java beginners.

3. Java: The Complete Reference


In “Java: The Complete Reference, Eighth Edition,” popular programming author Herb Schildt covers all you need to know about writing, building, debugging, and running Java programmes. This comprehensive volume covers the whole Java language, including syntax, keywords, and core programming concepts, and has been updated for Java Platform, Standard Edition 7 (Java SE 7). You’ll also learn about the key components of the Java API library. Swing, JavaBeans, servlets, and applets are all addressed, with real-world examples to demonstrate how they function. Try-with-resources, strings in switch, type inference with the diamond operator, NIO.2, and the Fork/Join Framework are all covered in detail.

4. Cracking the Coding Interview


Cracking the Coding Interview is well worth your time and money if you’re ready to start interviewing with FAANG firms. Everything from the interview procedure to unique scenarios, pre-interview preparation to behavior questions, Big O to technical questions, and 189 real-world programming problems are covered.

5. Introduction to Algorithms


This book examines a wide range of algorithms in depth while making their creation and analysis accessible to readers of all levels. Each chapter is self-contained and can be utilized as a study unit on its own. The algorithms are given in English and pseudocode that anyone who has done some programming may understand. Without losing the depth of information or mathematical rigor, the explanations have been kept simple.

6. Data Structures And Algorithms Made Easy


“Data Structures And Algorithms Made Easy: Data Structures and Algorithmic Puzzles” addresses questions about complex data structures and algorithms. Because each problem has several solutions and the book is written in C/C++, it may be used as an interview and test preparation tool for computer scientists.
Easy Data Structures and Algorithms: Data Structures and Algorithmic Puzzles is a collection of solutions to a variety of difficult problems involving data structures and algorithms. Any expert in computer science will find it useful. It may be used as a reference manual for computer science professionals. This book will assist you in preparing for campus interviews, exams, and employment. In a word, this book presents solutions to a wide range of challenging data structures.

7. The Algorithm Design Manual


The “mystery” of building algorithms and measuring their usefulness and efficiency is removed in this substantially extended and updated third edition of the best-selling classic. The book currently serves as the fundamental textbook for algorithm design classes, while also serving as the foremost practical reference guide on algorithms for programmers, researchers, and students, with updates to the first and second editions.

The user-friendly format The Algorithm Design Manual makes combinatorial algorithms technology accessible to anybody, with a focus on design rather than analysis. The first section, Techniques, explains how to develop and analyse computer algorithms in a clear and understandable manner. The second section, Resources, has a library of algorithmic resources, implementations, and a wide bibliography for browsing and reference.

8. Eloquent JavaScript


Eloquent JavaScript goes beyond the cut-and-paste scripts found in recipe books to teach you how to write elegant and effective code. Variables, control structures, functions, and data structures are among the first programming concepts you’ll study. After that, you’ll dive into JavaScript’s higher-order functions, closures, and object-oriented programming.

You’ll learn how to: Understand the principles of programming and best practises. By combining the capabilities of functional and object-oriented programming, regular expressions may be used to quickly analyse and edit text. Errors and browser incompatibilities should be handled compassionately. Handle browser events and DOM modifications.

9. Let Us C


The book’s simplicity and storytelling style set it out from the packed shelves of C Programming books. These two characteristics have been present in all six prior versions of this book. Today’s C programmer must not only learn the language’s complexity and nuances, but also deal with its use in systems such as Windows and Linux. This book does an excellent job of covering all three areas of C programming.

10. Head First Design Patterns


This book teaches you the patterns that matter, when and why to use them, how to apply them to your own ideas, and the object-oriented design concepts that underpin them. Join the hundreds of thousands of developers who have used Head First Design Patterns to enhance their object-oriented design abilities.

11. The Basics of Bitcoins and Blockchains


Learn about the history and fundamentals of cryptocurrencies and blockchains: There is a wealth of information available about bitcoin and blockchains. However, most of this information may be incomprehensible to the untrained. The Basics of Bitcoins and Blockchains seeks to give an easy-to-understand introduction to this new money and the groundbreaking technology that underlies it.

12. Database System Concepts


Database System Concepts is a classic and essential work in database education. It presents the fundamental concepts of database management in an easy-to-understand manner, allowing students to begin working with databases straight away.

The text is aimed towards junior/senior undergraduate database courses or first-year graduate database courses. It also includes additional information that may be utilized as a supplement or as a prelude to a more advanced course.

13. Python Crash Course


Look no further if you need to learn Python as soon as possible. Python Crash Course is designed to get novice Python programmers up and running quickly.
Learn the fundamentals of programming quickly using a project-based approach, so you can focus on what you want to build: websites, data visualization, online apps, or even programming a Raspberry Pi. Python Crash Course is the world’s best-selling Python book.

14. Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems


“Foundations of data systems” provides an excellent overview of data systems. This section begins by discussing desired database qualities such as dependability, scalability, and maintainability. Database concepts such as the classic relational model, the document model, and graph-based models are investigated. The implementation of data storage and retrieval in databases is then thoroughly explained.
You will learn about SStables, LSM trees, and B-Trees, as well as how they are employed in databases. Data warehousing and column-oriented databases are thoroughly discussed. The distinctions between OLTP and OLAP are presented in a tabular manner. There is a nice introduction to message brokers, protocolbuf, thrift, and avro.

15. Object-Oriented Programming with C++


The book’s goal is to provide a comprehensive enrichment of knowledge in the domain of object-oriented programming using C++ as the implementation language. The author has utilized simple language to convey important principles of object-oriented programming and to aid readers’ comprehension. The same ideas have been implemented in solved examples written in the C++ programming language. The book retains its original style of straightforward writing and includes plenty of solved examples, programming exercises, and additional practice problems.

If You ❤️ My Content! Connect Me on Twitter or Supports Me By Buying Me A Coffee☕👇🏼

Buy Me A Coffee

Source link

Striver's SDE Sheet Journey – #15 Majority Element (>N/2 times)

Problem Statement :-
Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.


Input : nums = [2,2,1,1,1,2,2]

Result : 2

Solution 1

using sorting,we can easily find the majority element in an array.
lets understand this approach step by step.

step-1 sort the array nums.

stpe-2 initialize three variables max = 0, count = 1, majEle = 0 .

step-3 run a loop from i=1 to n-1.

1. increase counting if the adjacent elements are the same..
if nums[i] == nums[i+1] then count++

2. if not nums[i] == nums[i+1], start recounting for new majority element.

3. if count > max then re-assign new max & majEle


class Solution 
    public int majorityElement(int[] nums) 

        if(nums.length == 1) return nums[0];

        int max =0;
        int majEle = 0;

        int count = 1;

        for(int i=0; i< nums.length-1; i++)
            if(nums[i] == nums[i+1])

                count = 1;

             if(count > max) 
                    max = count ;
                    majEle = nums[i];

        return majEle;


Time Complexity : O(nlogn) + O(n)
Space Complexity : O(1)

Solution 2

by using Boyer–Moore majority vote algorithm, we can solve this problem in O(n) time complexity

in this algorithm, we increase or decrease the count of the majority element, in the last, we will get our majority element.

step-1 initialise two variables majEle = nums[0], count = 1

step-2 run a loop from i=1 to n, then

1. if we found the majEle, increase the count by 1
2. if not majEle, decrease the count by 1
3. if count become 0 then, re-initialse majEle & count


class Solution 
    public int majorityElement(int[] nums) 

        int majEle = nums[0];
        int count = 1;

        for(int i=1; i<nums.length; i++)

            if(count == 0)
                majEle = nums[i];

            else if(nums[i] == majEle)

        return majEle;


Thank you for reading this article. save it for future use.
if you found something, let me in the comment section.

Source link

13+ Free Development Certification to get in 2021

Certification Course helps a person to grandstand his capability, responsibility for the calling, construct aptitude in his expert branch of knowledge, and assists with work progression. It’s anything but an assignment procured by an individual giving a sort of confirmation to the organization of his abilities of playing out a task.

So here in this post I am bringing 19 free certification you can earn in 2021.

Background Remover


Slazzer is an AI-based photograph editing application that can without much of a stretch eliminate or change the foundation in your pictures. This instrument is not difficult to utilize and is great for online advertisers who routinely manage photographs and are hoping to save time, cash, and exertion.

Key Features

Utilizing this tool is speedy and simple as you don’t need to manually edit the photograph while eliminating or changing the foundation. One more beneficial thing here is that the entire course of background editing essentially begins with transferring a picture and sitting tight for a couple of moments just to get the moment result.


Paid plan starts at $13 per month for 100 credits. The free version offers low-resolution images.**

Above were some free certification you can earn in 2021 for free. Alternatively I will ask you to visit the below websites to see a range of free certification in mane other fields too.

Want to add more? Comment down below

Source link

Some Javascript Methods: slice() & splice()

Hey everyone, my name is Dez and I am new to programming as well. I wanted to share my understandings of some javascript methods I have learned. If I messed anything up PLEASE feel free to correct me and I will change it. Also if you want to add some more methods or tips/tricks in the comments that will be awesome!

1.) slice()

Slice is a non-mutating method (this means it does not change the original array). This method extracts selected items from an array and returns the extracted items. The slice method looks like this array.slice(from, until); Now you might be confused with the “until” part. SO I will do my best to explain it because the until part was CONFUSING!
What I found was that the “until” part is NOT the end index, instead, it’s until ANOTHER element index. For example, let’s say I want to slice an array from index 2 to index 4 we will write array.slice(2,5) Think of this 5 as in “STOP AT INDEX 5 BUT DO NOT INCLUDE”. Now let’s create an instance and try to use slice to get what we wanted

EX 1-1:
myHobbies.slice example:

  • The following code is an array with my hobbies as elements
    const myHobbies = ["Muay Thai", "Boxing", "Programming", "Lifting weights", "Learning about Artificial Intelligence"]

  • Let’s say we can extract Programming, Lifting Weights, and Learning about Artificial Intelligence. We will write it as follows:
    myHobbies.slice(2, 5)
    This will extract my desired items and if I wanted to we can save them into a variable because the method RETURNS my selected items into a new array. So if I were to console.log what I wrote above I will get:
    ['Programming', 'Lifting Weights', 'Learning about Artificial Intelligence']
    Now if I were to console.log myHobbies I will get:
    ["Muay Thai", "Boxing", "Programming", "Lifting weights", "Learning about Artificial Intelligence"]
    This is because this method is non-mutating remember?

2.) splice()

Splice IS NOT THE SAME AS SLICE!!! A lot of devs get this confused because the names are similar. Now splice CHANGES an array by adding or removing elements from the array.

  • Removing Elements with splice()
    In order to remove elements using splice, we will need to provide the method with the index of the element along with the number of elements to be removed. It will be written as such: array.splice(index, number of elements); Where “index” is the starting point and number of elements is how many elements we want to be removed starting from our desired start point going up. Now if we fail to include a second argument every single element starting from your start point and up will be REMOVED. Now let’s see it in action

EX 2-1:
Now let’s say we have the same array as before which is const myHobbies = ["Muay Thai", "Boxing", "Programming", "Lifting weights", "Learning about Artificial Intelligence"]. Now let’s say we got injured and we are no longer interested in lifting weight. We also figured that we no longer want to learn about artificial intelligence. Now to remove these 2 elements from our myHobbies array we can use the splice method!
What this does is that it will begin on index 3 which is “Lifting Weights” and will REMOVE 2 elements. These elements will be the starting point and the next element. This means if we console.log myHobbies we will see [“Muay Thai”, “Boxing”, and “Programming”] Awesome right?

  • Adding Elements
    In order to add elements, we will need to pass them as the 3rd, 4th, 5th …nth parameter. Depending on how much you want to add of course. So it will look like this array.splice(index, number of elements, element, element, element)

EX 2-2:

Let’s look at our previous array again which is const myHobbies = ["Muay Thai", "Boxing", "Programming", "Lifting weights", "Learning about Artificial Intelligence"]. Let’s say we picked up new hobbies and we want to add them. In order to NOT remove anything, but add new elements we can do it like this.
myHobbies.splice(5,0, 'Machine Learning', 'Running','CyberSecurity')

Now if we console.log myHobbies we will see [ ‘Muay Thai’, ‘Boxing’, ‘Programming’, ‘Lifting weights’, ‘Learning about Artificial Intelligence’, ‘Machine Learning’, ‘Running’, ‘CyberSecurity’] NOTE: Notice how I put 5 as the index. This means I wanted to start on the 5th index which is “Learning about Artificial Intelligence” and add it at the end. You can begin in ANY index and add it in. This means you can throw in some elements in the center if you really wanted to.

Source link

Firing on all cylinders(Part 1): Understanding object value lookup in JavaScript interpreters and the rise of hidden classes

There is a lot of information around writing performant JavaScript and optimizing your code for the v8 engine. When you are reading through this information you will see a lot of phrases like inline caching, hidden classes, and memory offset; but what does it all mean? You’ll come across quick one-liners about “always instantiating your object properties in the same order” or, better yet, “assign all of the objects properties in the constructor”. You try to dive into the documentation only to see branching charts with a million tiny words in it that look more like Harry Potter’s family tree. At the end of all this, you end up just trying to commit those one liners to memory without fully understanding why.

In this series, I am going to attempt to explain these concepts in a way where we don’t need pages of flow charts, and with relatable examples (not just look at this code).

What to expect

We will start by going over the difference between dynamic and non-dynamic languages (mostly pertaining to how they store objects in memory). Then, in part 2, we will dive into the v8 engine and the methods it uses to efficiently handle the concepts we discuss in part 1. Also, in part 2, I will describe the common pitfalls and ways you can increase the performance of your code. However, you can’t make the code better without first understanding the why.

Before we begin

Although I am going to try and explain these concepts in an approachable way, these are not easy concepts to grasp. Most developers can go their entire career without digging into the minute details of how a particular JavaScript engine accesses objects in memory.

Modern JavaScript Interpreters, like v8, are amazing tech and mostly handle all of this for you. Furthermore, with TypeScript, you have a compiler that can help keep you from making a lot of the common mistakes that can lead to a decrease in performance. However, taking the time to try and understand what is happening under the hood can go a long way.

The dynamic language

JavaScript is a dynamic programming language. This means that you can add, remove, and change (the type) property values of objects after they are initialized. Let’s look at the following code:

// Define a simple constructor function for an employee
const employee = function(salary, position) 
  this.salary = salary;
  this.position = position;

// Instantiate a new employee
const newHire = new employee(50000, 'sales');

// Dynamically add the employee's desired pay day
newHire.payDay = 'Saturday';

After the employee object is created, their preferred payDay is added dynamically. This is all perfectly valid JavaScript. It will run just fine and the newly hired employee will get paid every Saturday.

The difference between a non-dynamic programming language (meaning all of an objects properties are fixed before compilation) is that new properties cannot be added or removed at runtime. The benefit to a language being non-dynamic is that the values of these properties (or pointers) can be stored in memory with a fixed offset (an integer indicating the displacement between the beginning of an object in memory and any given property). This offset can be easily determined based on the properties type.

Skrrtttt… offset?!?! displacement?!?! You said this would be easy to follow and relatable!

You’re right, this is why I decided to do this blog in two parts.

Memory storage displacement (offset)

The easiest way to explain this is with a simple data structure like an array:

const array = ['value1', 'value2', 'value3', 'value4'];

We know we can access a value in that array using its index:

array[2]; // this will get us the item at index 2 ('value3')

If the first value ('value1') is at memory position 0, moving two places to the right will give you ('value3'). So 'value3' has an offset of 2 from the start of where the array is stored in memory.

This is simple enough for an array, however not all objects are stored in memory sequentially like an array is. With more complex objects, like the employee function above, you can’t be sure where the object, and its properties, will be stored. Thus making it harder to determine the offset between the objects ‘shell’ (to keep it simple) and its properties. You could have the ‘shell’ of the object (function employee() ) at position 0, then its property this.salary at position 6 with other objects in between.

Back to dynamic vs. non-dynamic

In order to keep up with these offset values, non-dynamic languages (i’ll use Java in this case) create a fixed object layout. This layout (or mapping) cannot be changed (as in changing the type), added too, or removed from at runtime. The offset is written in stone, making it easy (usually one instruction) to grab any property value of a given object.

Since you can add, remove, and even change a properties type in JavaScript at runtime, the interpreter has to allocate a new space in memory and then add a new mapping (offset value) back to the object for every change. It will then have to go back through and clean up the memory by a process called garbage collection. In order to keep up with these changes, JavaScript interpreters needed a data structure that can change at runtime.

Hash Tables

Instead of using a fixed object layout, like in the non-dynamic Java, most JavaScript interpreters use a dictionary like structure (based on a hash function) to store the objects property values in memory. This is often referred to as a hash table.

A hash table, simply put, is a collection of key/value pairs. A over-simplified version of what the employee object might look like in a hash table would be keys mapped to the values of where the employee object starts in memory, along with the offset value of each of it properties. We can attempt to replicate this using a Plain Old JavaScript Object:

const hashTable = {
        'memoryStart': 0,
          'salary_offset': 4,
          'position_offset': 5
        'memoryStart': 12,
          'salary_offset': 8,
          'position_offset': 12

If you wanted to add a property to the table (after the value is added in memory), you can simply update that objects ‘bucket’ in the table.

By doing this, the interpreter is able to add properties to the object anywhere in memory, because it has a dictionary (the hash table) keeping track of where the properties are located and what object they belong too.

Because of this, grabbing the properties value from a hash table is more computationally expensive (more instructions) than the fixed object layout of a non-dynamic language. Instead of having a direct one-to-one mapping of object/property to the offset of where the value is located, the interpreter must search through the hash table.

I won’t go more into hash tables, and this is an extremely over-simplified example. If you wanted to learn more you can start here and I have added a very nice blog at the bottom of this post. Just know it is extremely inefficient compared to what is coming next.

Firing on all cylinders

Since using hash tables to get property values is so inefficient, the JavaScript engine NodeJS uses, ‘v8’, takes a different approach. This approach is built around using Hidden Classes and made faster by Inline Caching.

In part 2 of this series we will dive into hidden classes and inline caching. Once you better understand the concepts, we can get into techniques you can use to make sure your JavaScript is as performant as it can be.

Further reading

Blog: Hash tables

Blog: How Java stores objects in memory

The official v8 engine blog

MDN JavaScript types and data structures

Wikipedia article on Offset

Source link

Thirty Days of Rust: Day Five

Today I wanted to take it easy a little bit and try some WebAssembly with Rust. Over the years I’ve gotten very used to JavaScript, but now that I’m doing this challenge, I wanted to dip my feet into WebAssembly, so that’s exactly what I did. I found a book that basically told me everything I needed to know, and then I got started.

Rust Setup

So instead of a new Rust app, I needed to make a Rust lib, which I could do with:

$ cargo new day5 --lib

Then I added two things to my Cargo.toml so it looked like this:

name = "day5"
version = "0.1.0"
edition = "2021"

crate-type = ["cdylib", "rlib"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

wasm-bindgen = "0.2.78"

Then I went ahead and installed wasm-pack with cargo:

$ cargo install wasm-pack

Rust Code

The only thing I wanted this app to do was add two numbers together. It’s probably too simple for this challenge to really mean anything, but I didn’t want to spend too much time on this because tomorrow I want to rebuild my hangman game in the browser and I figured today could be a little bit shorter.

use wasm_bindgen::prelude::*;

pub fn add(n1: i32, n2: i32) -> i32 
    return n1 + n2;

So that was simple, as I expected and now I just had to pack it together with:

$ wasm-pack build

JS Setup

$ pnpm init wasm-app www
$ cd www
$ pnpm i

That’s all, now I just imported the wasm file and console logged the result of the add function:

import * as wasm from "../pkg";

console.log(wasm.add(21, 19));

Now I could just run pnpm serve and open up localhost:8080 to get to my app. When I opened up the console, it showed the logged value of 40.
That’s about it from me today, but I look forward to tomorrow and sorry if this one was a little less exciting.

Source link