【问题标题】:Gson - Serialize list of objects with nested list of objects - Takes agesGson - 使用嵌套的对象列表序列化对象列表 - 需要很长时间
【发布时间】:2015-11-17 14:09:17
【问题描述】:

在序列化对象列表时,我遇到了严重的性能问题,其中每个对象都包含其他对象的列表:

class Author {
    private String name;
    private List<Book> books;
}

class Book {
    private String name;
}

我有一个类似的结构。当我有一个包含 8000 个元素的列表,并且每个作者实例有 6 本书时,此代码大约需要 40 秒才能运行:

new Gson().toJson(authors);

我不认为这是正常的吗?我正在使用 Gson 2.4 版。

【问题讨论】:

  • 如果你有大文件要转换,试试 jackson

标签: java json serialization gson


【解决方案1】:

我已经用你的数据准备了一个例子

package gson;

import java.util.ArrayList;
import java.util.Random;

import com.google.gson.Gson;

public class GsonExample {

    private static final String[] arrNames = {"Jay","Willy","John","Gary","Franklin","Renee"};
    private static final String[] arrBooks = 
        {"The Hitchhiker's Guide to the Galaxy",
        "Pride and Prejudice and Zombies",
        "I Was Told There'd Be Cake",
        "The Hollow Chocolate Bunnies of the Apocalypse",
        "To Kill a Mockingbird",
        "The Unbearable Lightness of Being"};

    private static final int NUM_AUTHORS    = 8000;
    private static final int NUM_BOOKS      = 6;

    private static final boolean printResults   = true;

    public static void main(String[] args) {

        long startTime = System.currentTimeMillis();
        long estimatedTime = 0;

        ArrayList<Author> authors = new ArrayList<Author>();
        for (int i = 0; i < NUM_AUTHORS; i++) {
            authors.add(getDummyAuthor());
        }
        String json = new Gson().toJson(authors);

        if (printResults) {
            System.out.println(json);
        }

        estimatedTime = System.currentTimeMillis() - startTime;

        System.out.println("Estimated time: " + estimatedTime + " miliseconds");
    }

    private static Author getDummyAuthor() {
        Author author = new Author();
        ArrayList<Book> books = new ArrayList<Book>();
        Random rand = new Random();
        int randomValue = rand.nextInt(arrNames.length);
        String authorName = arrNames[randomValue];

        for (int i = 0; i < NUM_BOOKS; i++) {
            books.add(getDummyBook(i));
        }
        author.setName(authorName);
        author.setBooks(books);

        return author;
    }

    private static Book getDummyBook(int ixBook) {
        String bookName = arrBooks[ixBook];
        Book book = new Book(bookName);
        return book;
    }
}

平均时间约为 10 秒(打印数据)。不打印的时间约为 300-400 毫秒。你有可能在做某种循环吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多