Slide 1

Slide 1 text

~ Understanding Memory Behavior on NodeJS The memory concept in 
 JavaScript engines @raphamundi

Slide 2

Slide 2 text

Raphael Amorim This guy seems like a nice person, but he doesn’t. Seriously. He likes topics related to JavaScript, Python, Clojure, WebGL, Algorithms and sometimes force some git push. 
 Working most part of his time in useless globo.com • js foundation/jQuery member • Mozillian • Metido a besta • @raphamundi This guy seems like a he doesn’t. Seriously. related to JavaScript, WebGL, Algorithms and some git push. 
 Working most part of h open source projects. some git push. 
 Working most part of his open source projects.

Slide 3

Slide 3 text

talentos.globo.com

Slide 4

Slide 4 text

[Question] Would you board a plane programmed by JavaScript?

Slide 5

Slide 5 text

[Question] Would you board a plane programmed by JavaScript? 54% Yes 32% No 14% I don’t know

Slide 6

Slide 6 text

Motivations (?)

Slide 7

Slide 7 text

Developers (not all) don’t considers (or just doesn’t know) how tricky can be memory management in Nodejs.

Slide 8

Slide 8 text

INTRO

Slide 9

Slide 9 text

Computer memory is any physical device capable of storing information temporarily or permanently.

Slide 10

Slide 10 text

Computer memory is any physical device capable of storing information temporarily or permanently.

Slide 11

Slide 11 text

the ‘ is 
 from 
 other ‼

Slide 12

Slide 12 text

Memory is Limited

Slide 13

Slide 13 text

NODEJS

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

Initially created for Google Chrome, but it can also be used as a standalone.

Slide 16

Slide 16 text

83%* of all INTERPRETERS AREN’T IN JAVASCRIPT *invented number

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

NodeJS is a C++ program controlled via V8 *https://github.com/v8/v8/wiki/Getting%20Started%20with%20Embedding

Slide 19

Slide 19 text

Dynamic memory allocation

Slide 20

Slide 20 text

Dynamic memory allocation Weakly typed

Slide 21

Slide 21 text

Dynamic memory allocation Weakly typed "V8's stop-the-world"

Slide 22

Slide 22 text

Dynamic memory allocation Weakly typed "V8's stop-the-world" "generational"

Slide 23

Slide 23 text

V8: garbage collection

Slide 24

Slide 24 text

Every program that consumes memory requires a mechanism for reserving and freeing space.

Slide 25

Slide 25 text

In C and C++, this is accomplished by malloc() and free() Every program that consumes memory requires a mechanism for reserving and freeing space.

Slide 26

Slide 26 text

char * buffer; buffer = (char*) malloc (42); // Do something with buffer free (buffer);

Slide 27

Slide 27 text

char * buffer; buffer = (char*) malloc (42); // Do something with buffer free (buffer); What this means?

Slide 28

Slide 28 text

In this case (C++) the programmer is responsible for freeing heap memory that is no longer required.

Slide 29

Slide 29 text

Programmers make mistakes.

Slide 30

Slide 30 text

/* Allocate 30 bytes to house a string */ char* str = new char [30]; /* Clear those 30 bytes and make str point nowhere */ delete [] str;

Slide 31

Slide 31 text

/* Allocate 30 bytes to house a string */ char* str = new char [30]; /* Give str another memory address with the first one gone forever */ str = new char [60]; delete [] str;

Slide 32

Slide 32 text

Fail to remove data that can not be referenced.

Slide 33

Slide 33 text

When a portion of memory allocated for certain operation is not released when it's no longer needed.

Slide 34

Slide 34 text

Fail to remove data that can not be referenced. When a portion of memory allocated for certain operation is not released when it is no longer needed. It’s a 
 Memory Leak

Slide 35

Slide 35 text

Garbage collection is double-edged sword

Slide 36

Slide 36 text

positive side: languages that use it become more simple.

Slide 37

Slide 37 text

negative side: no control of memory.

Slide 38

Slide 38 text

ECMAScript specification doesn't expose any interface to garbage collector.

Slide 39

Slide 39 text

Performance of garbage collected languages is not strictly better or worse than languages without managed memory!

Slide 40

Slide 40 text

V8: memory scheme

Slide 41

Slide 41 text

Resident Set ~ V8 uses a scheme similar to the Java Virtual Machine and divides the memory into segments ~

Slide 42

Slide 42 text

Resident Set Code Segment Stack Heap Used Heap

Slide 43

Slide 43 text

~Code Segment~ The actual code being executed

Slide 44

Slide 44 text

[|||||] Stack Variable

Slide 45

Slide 45 text

char *buff[500]

Slide 46

Slide 46 text

Contains all value types with pointers referencing objects on the heap.

Slide 47

Slide 47 text

[|||||] Heap Variable

Slide 48

Slide 48 text

char *buff = (char *)malloc(500)

Slide 49

Slide 49 text

A memory segment dedicated to storing reference types like objects, strings and closures.

Slide 50

Slide 50 text

process.memoryUsage() *https://nodejs.org/api/process.html#process_process_memoryusage

Slide 51

Slide 51 text

console.log(process.memoryUsage()); { rss: 4935680, heapTotal: 1826816, heapUsed: 650472, external: 49879 }

Slide 52

Slide 52 text

console.log(process.memoryUsage()); { rss: 4935680, heapTotal: 1826816, heapUsed: 650472, external: 49879 } rss refer to resident set size.

Slide 53

Slide 53 text

console.log(process.memoryUsage()); { rss: 4935680, heapTotal: 1826816, heapUsed: 650472, external: 49879 } heapTotal and heapUsed refer to V8's memory usage.

Slide 54

Slide 54 text

console.log(process.memoryUsage()); { rss: 4935680, heapTotal: 1826816, heapUsed: 650472, external: 49879 } external refers to the memory usage of C++ objects bound to JavaScript objects managed by V8.

Slide 55

Slide 55 text

Terms: generationals

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

How Memory Allocation works in Nodejs

Slide 58

Slide 58 text

// allocation for Number var num = 42; // allocation for String var str = “my string”;

Slide 59

Slide 59 text

// allocation for Number var num = 42; // allocation for String var str = “my string”; Rvalue Lvalue

Slide 60

Slide 60 text

// each element is a not named reference var arr = [1, null, "ABC"]

Slide 61

Slide 61 text

// each element is a not named reference var arr = [1, null, "ABC"] *In-Object slack tracking

Slide 62

Slide 62 text

In-Object slack tracking

Slide 63

Slide 63 text

// each element is a not named reference var arr = [1, null, "ABC"] *In-Object slack tracking *overflow array

Slide 64

Slide 64 text

// callable - executable object function fun(a) { return a + 10 }

Slide 65

Slide 65 text

// functions with expressions do object allocation myElement.addEventListener(‘click’, () => {
 myElement.style.opacity = 0
 }, false)

Slide 66

Slide 66 text

Cyclic reference

Slide 67

Slide 67 text

// cycle allocation var a = {} var b = {} a.c = b b.d = a

Slide 68

Slide 68 text

Hightlight: Garbage Collector Sample

Slide 69

Slide 69 text

> var myObject = {
 person: { name: "raphael", age: 21, }
 }

Slide 70

Slide 70 text

var myObject = {
 person: { name: "raphael", age: 21, }
 } > var anotherObject = myObject

Slide 71

Slide 71 text

var myObject = {
 person: { name: "raphael", age: 21, }
 } var anotherObject = myObject > myObject = 1

Slide 72

Slide 72 text

> var yetAnotherObject = anotherObject.person person: { name: "raphael", age: 21, }
 } var anotherObject = myObject myObject = 1

Slide 73

Slide 73 text

> anotherObject = “some-random-string” var yetAnotherObject = anotherObject.person }
 } var anotherObject = myObject myObject = 1

Slide 74

Slide 74 text

> yetAnotherObject = null anotherObject = “some-random-string” var yetAnotherObject = anotherObject.person var anotherObject = myObject myObject = 1

Slide 75

Slide 75 text

Hightlight: Building A Leak

Slide 76

Slide 76 text

easy, right?

Slide 77

Slide 77 text

function LeakingClass() { // do-nothing }

Slide 78

Slide 78 text

function LeakingClass() { // do-nothing } var leaks = []

Slide 79

Slide 79 text

function LeakingClass() { // do-nothing } var leaks = [] setInterval(function() { for (var i = 0; i < 100; i++) { leaks.push(new LeakingClass) } console.error('Leaks: %d', leaks.length) }, 1000)

Slide 80

Slide 80 text

it’s so fun, let’s create another!

Slide 81

Slide 81 text

const developer = { name: “amorim”, company: “globocom” } doWork(() => { const data = developer.name // doing a bunch of work })

Slide 82

Slide 82 text

one more!

Slide 83

Slide 83 text

const http = require(‘http') const server = http.createServer((req, res) => { for (var i=0; i<1000; i++) { server.on('request', function LeakFunc() {}) } res.end(‘Hello, The Conf!’) }).listen(8585, ‘127.0.0.1') server.setMaxListeners(0) console.log(`Server running at 127.0.0.1:8585/. Process PID: ${process.pid}`)

Slide 84

Slide 84 text

Hightlight: Debugging A Leak

Slide 85

Slide 85 text

let’s get back to the leak examples

Slide 86

Slide 86 text

function LeakingClass() { // do-nothing } var leaks = [] setInterval(function() { for (var i = 0; i < 100; i++) { leaks.push(new LeakingClass) } console.error('Leaks: %d', leaks.length) }, 1000) leak.js

Slide 87

Slide 87 text

node --inspect leak.js

Slide 88

Slide 88 text

No content

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

Hint: You can also send the SIGUSR1 signal to an existing node process to enable the inspect mode as you need it.

Slide 92

Slide 92 text

Hint2: It's important to use named constructors, otherwise the heap snapshots will not produce useful outputs for you.

Slide 93

Slide 93 text

const http = require(‘http') const server = http.createServer((req, res) => { for (var i=0; i<1000; i++) { server.on('request', function LeakFunc() {}) } res.end(‘Hello, The Conf!’) }).listen(8585, ‘127.0.0.1') server.setMaxListeners(0) console.log(`Server running at 127.0.0.1:8585/. Process PID: ${process.pid}`) server-leak.js

Slide 94

Slide 94 text

npm i memwatch-next or npm i node-memwatch

Slide 95

Slide 95 text

No content

Slide 96

Slide 96 text

› ab -n 1000 -c 100 http://127.0.0.1:8585/

Slide 97

Slide 97 text

No content

Slide 98

Slide 98 text

No content

Slide 99

Slide 99 text

There’s a lot of tools to help you! - node-memwatch - node-heapdump - node-inspector - nodetime - v8-profiler - memwatch-next - ...

Slide 100

Slide 100 text

const developer = { name: “amorim”, company: “globocom” } doWork(() => { const data = developer.name // doing a bunch of work }) closure-leak.js

Slide 101

Slide 101 text

const developer = { name: “amorim”, company: “globocom” } doWork(() => { const data = developer.name // doing a bunch of work developer = null })

Slide 102

Slide 102 text

Hightlight: Wrap up

Slide 103

Slide 103 text

"Even valid code can cause memory leaks."

Slide 104

Slide 104 text

theThing = null

Slide 105

Slide 105 text

References: - https://blog.codeship.com/understanding-garbage- collection-in-node-js - https://speakerdeck.com/pantuza/memory-leak-em- javascript - https://medium.com/@_lrlna/garbage-collection-in-v8-an- illustrated-guide-d24a952ee3b8 - http://jayconrod.com/posts/55/a-tour-of-v8-garbage- collection - https://github.com/v8/v8/wiki

Slide 106

Slide 106 text

References: - https://stackoverflow.com/questions/19550253/memory- leaks-and-closures-in-javascript-when-and-why - https://www.nearform.com/blog/self-detect-memory-leak- node/ - https://github.com/felixge/node-memory-leak-tutorial - https://stackoverflow.com/questions/6261201/how-to- find-memory-leak-in-a-c-code-project

Slide 107

Slide 107 text

Thank You @raphamundi