A little summary of code optimization

Many times, in order to catch up with the project progress, or there is no suitable code review mechanism, and the level of each programmer is different. The following points are some of the adjustments made recently when optimizing the interface.

  1. If you use a loop to continuously operate the database, please put this loop in the service layer and use @Transactionalit, so as to ensure that multiple database operations are performed in one transaction, and the commit transaction will not be continuously opened. It is not recommended to put it in the controller layer or action layer.
    Example code is as follows:

    @Transactional
    @Override
    public List<Content> collectContents(Set<String> contentIds) {
        if (contentIds.isEmpty()) {
            return new ArrayList<>();
        }
    
        Integer[] ids = contentIds.stream()
                .map(id -> Integer.parseInt(id))
                .collect(Collectors.toList())
                .toArray(new Integer[contentIds.size()]);
    
        return dao.queryContentsInOne(ids);
    }
  2. If you need to obtain multiple keys or batch operations of redis, it is recommended to use pipeline to reduce network communication overhead.
    Example code is as follows:

    Pipeline pipeline = jedis.pipelined();
    
        List<String> uIds = new LinkedList<>(followingUsers);
        for(String userId : uIds) {
            pipeline.exists(getFormatKeyStr(USER_CONTENT_ZSET, userId));
        }
Pipeline zaddPipeline = jedis.pipelined();
        if(Objects.nonNull(followingUpUserContents) && followingUpUserContents.size() > 0) {
            followingUpUserContents.forEach(content -> {
                zaddPipeline.zadd(getFormatKeyStr(USER_CONTENT_ZSET, content.getUser().getId()),
                        content.getSortDate().getTime(),
                        String.valueOf(content.getId()));
            });

            zaddPipeline.sync();
        }
  1. Familiarize yourself with the definition structure of the data table, the type and length of each field, and which indexes are established, which indexes are required, and which ones can be removed, and then use the explain command to check whether the SQL statement you want to write is used. index.
  2. The OOM overflow was encountered in the project. The reason was that Hibernate used redis as the secondary cache, but because redis required a lot of network communication, it was replaced by Ehcache, and the result was OOM. The reason is that Ehcache needs a lot of memory to cache query results, and not much memory is allocated at the beginning. The solution is to increase the memory.

  3. Always remember null and empty situations, you can use Optional to solve.
    The example code is as follows:
    ```
    package crazy;

import java.util.Optional;

class Company {
private String name;
private Optional office;

public Company(String name, Optional<Office> office) {
    this.name = name;
    this.office = office;
}

public String getName() {
    return name;
}

public Optional<Office> getOffice() {
    return office;
}

}

class Office {
private String id;
private Optional

address;

public Office(String id, Optional<Address> address) {
    this.id = id;
    this.address = address;
}

public String getId() {
    return id;
}

public Optional<Address> getAddress() {
    return address;
}

}

class Address {
private Optional street;
private Optional city;

public Address(Optional<String> street, Optional<String> city) {
    this.street = street;
    this.city = city;
}

public Optional<String> getStreet() {
    return street;
}

public Optional<String> getCity() {
    return city;
}

}

public class OptionalDemo1 {

public static void main(String[] args) {
    Optional<Address> address1 = Optional.of(new Address(Optional.ofNullable(null), Optional.of("New York")));
    Optional<Office> office1 = Optional.of(new Office("OF1", address1));
    Optional<Company> company1 = Optional.of(new Company("Door Never Closed", office1));

    // What is the street address of company1?
    // In which city company1 is located?
    Optional<Office> maybeOffice = company1.flatMap(Company::getOffice);
    Optional<Address> maybeAddress = office1.flatMap(Office::getAddress);
    Optional<String> maybeStreet = address1.flatMap(Address::getStreet);

    maybeStreet.ifPresent(System.out::println);
    if (maybeStreet.isPresent()) {
        System.out.println(maybeStreet.get());
    } else {
        System.out.println("Street not found.");
    }
    
    // shorter way
    String city = company1.flatMap(Company::getOffice)
            .flatMap(Office::getAddress)
            .flatMap(Address::getStreet)
            .orElse("City is not found.");
    
    System.out.println("City: " + city);
    
     // only print if city is not null
    company1.flatMap(Company::getOffice)
            .flatMap(Office::getAddress)
            .flatMap(Address::getCity)
            .ifPresent(System.out::println);

}

}
```

  1. If common optimizations are not obvious, consider using temporary tables.

The most important point is:
when writing code, don't just stare at the code, think about how the code you write is executed in memory or in the program.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324771613&siteId=291194637