Wilmar
Wilmar

Reputation: 568

LUA: add values in nested table

I have a performance issue in my application. I would like to gather some ideas on what I can do to improve it. The application is very easy: I need to add values inside a nested table to get the total an user wants to pay out of all the pending payments. The user chooses a number of payments and I calculate how much it is they will pay.

This is what I have:

jsonstr = "{    "name": "John",
    "surname": "Doe",
    "pending_payments": [
        {
            "month": "january",
            "amount": 50,
        },
        {
            "month": "february",
            "amount": 40,
        },
        {
            "month": "march",
            "amount": 45,
        },
    ]
}"

local lunajson = require 'lunajson'
local t = lunajson.decode(jsonstr)
local limit   -- I get this from the user
local total = 0;

for i=1, limit, 1 do 
    total = total + t.pending_payments[i].amount; 
end;

It works. At the end I get what I need. However, I notice that it takes ages to do the calculation. Each JSON has only twelve pending payments (one per month). It is taking between two to three seconds to come up with a result!. I tried in different machines and LUA 5.1, 5.2., 5.3. and the result is the same.

Can anyone please suggest how I can implement this better?

Thank you!

Upvotes: 1

Views: 172

Answers (2)

Wilmar
Wilmar

Reputation: 568

I found the delay had nothing to do with the calculation in LUA. It was related with a configurable delay in the retrieval of the limit variable.

I have nothing to share here related to the question asked since the problem was actually in an external element.

Thank @lfh for your replies.

Upvotes: 1

lhf
lhf

Reputation: 72312

For this simple string, try the test code below, which extracts the amounts directly from the string, without a json parser:

jsonstr = [[{    "name": "John",
    "surname": "Doe",
    "pending_payments": [
        {
            "month": "january",
            "amount": 50,
        },
        {
            "month": "february",
            "amount": 40,
        },
        {
            "month": "march",
            "amount": 45,
        },
    ]
}]]

for limit=0,4 do
    local total=0
    local n=0
    for a in jsonstr:gmatch('"amount":%s*(%d+),') do
        n=n+1
        if n>limit then break end
        total=total+tonumber(a)
    end
    print(limit,total)
end

Upvotes: 1

Related Questions