If you run this code
import asynchttpserver, asyncdispatch
var server = newAsyncHttpServer()
proc cb(req: Request) {.async.} =
await req.respond(Http200, "Hello World", newHttpHeaders())
waitFor server.serve(Port(8080), cb)
on start the memory usage is 1.2Mb, (nim c -r server.nim), but after like 50 requests it goes to 3.6Mb
I tried the same request with github.com/mattaylor/whip, it doesn't have this problem.
Is this ok or it's a memory leak?
For small things Nim will not free memory back to the OS but will keep the memory in a "free" block. Its much faster to get free memory from nim's internal allocator the ask the OS again. So your Nim memory will only grow and never shrink. This is usually not a problem as the free memory gets cold and the page unit just handles it.
You need to use Nim's internal memory counters: https://nim-lang.org/docs/gc.html#keeping-track-of-memory to see if it really leaked memory.
How do you check for memory usage? Using some thing like top will not work.
If you want to use top to check memory one thing you can do is compile with -d:useMalloc which will force your program to use the OS memory API directly but will slow down your program.
Note though, because Nim allocation is optimized for smaller things, when allocating large (I thank 1 GB buffers?) Nim will use the OS memory API instead of its internal system. Those large frees will show up in top.
Does this help?
Thanks, that was quite detailed explanation :)
I ran for i in {1..50}; do curl http://localhost:8080/; done
it goes up to 5.4MB and stays there, I just wonder why Whip allocates 1.2MB and doesn't move. Is there any difference between asynchttpserver and httpbeast in allocating buffers, or this is Nim thing?