Programing

JSON 대 데이터베이스의 직렬화 된 배열

lottogame 2020. 10. 31. 09:12
반응형

JSON 대 데이터베이스의 직렬화 된 배열


MySQL 데이터베이스에 JSON 데이터를 저장하는 것과 직렬화 된 배열의 장점과 단점은 무엇입니까?


  1. JSON 인코딩 () 및 디코딩 ()
    • PHP 버전> = 5.0.0
      • 중첩 제한은 20입니다.
    • PHP 버전> = 5.2.3
      • 중첩 제한은 128입니다.
    • PHP 버전> = 5.3.0
      • 512의 중첩 제한.
    • 작은 풋 프린트 대 PHP의 직렬화 문자열.
  2. 직렬화 () 및 직렬화 해제 ()
    • PHP 버전> = 4.0.0
      • PHP 데이터 유형 객체에서 메소드가 손실되지 않습니다.
      • __wakeup () 매직 메서드가 직렬화 해제되는 모든 객체에서 호출됩니다. (아주 세다)
      • 일부 공백 문자를 처리하는 데 몇 가지 문제가 있으므로이 함수를 사용 하여 base64 인코딩 문자열을 데이터베이스에 넣고 base64 디코딩 문자열을 데이터베이스에서 가져 오는 것이 가장 좋습니다 .

선택은 당신의 것입니다.


프로 JSON :

  • JSON 데이터는 PHP뿐만 아니라 다양한 언어에서 사용할 수 있습니다.
  • JSON 데이터는 사람이 읽고 쓸 수 있습니다.
  • 적은 공간을 차지합니다
  • 직렬화하는 것보다 JSON을 인코딩하는 것이 더 빠릅니다.

Pro 직렬화 어레이 :

  • JSON 디코딩보다 직렬화 해제가 더 빠릅니다.

주석에서 알 수 있듯이 JSON은 직렬화 배열보다 적은 공간을 차지합니다. 또한 JSON 또는 Serializing이 더 빠른지 확인했으며 놀랍게도 Serialize보다 JSON 인코딩이 더 빠릅니다. 하지만 JSON 디코딩보다 직렬화 해제하는 것이 더 빠릅니다.

다음은 테스트에 사용한 스크립트입니다.

<?php 
function runTime(){
      $mtime = microtime(); 
      $mtime = explode(' ', $mtime); 
      $mtime = $mtime[1] + $mtime[0]; 
      return $mtime; 
}
?> 
<pre>
<?php
$start = runTime();

$ser;

for($i=0; $i<1000; $i++){
    $a = array(a => 1, x => 10);
    $ser = serialize($a);
}
$total = runTime() - $start;
echo "Serializing 1000 times took \t$total seconds";
?>

<?php
$start = runTime();

$json;

for($i=0; $i<1000; $i++){
    $a = array(a => 1, x => 10);
    $json = json_encode($a);
}
$total = runTime() - $start;
echo "JSON encoding 1000 times took \t$total seconds";
?>

<?php
$start = runTime();

$ser;

for($i=0; $i<1000; $i++){
    $a = unserialize($ser);
}
$total = runTime() - $start;
echo "Unserializing 1000 times took \t$total seconds";
?>

<?php
$start = runTime();

$json;

for($i=0; $i<1000; $i++){
    $a = json_decode($json);
}
$total = runTime() - $start;
echo "JSON decoding 1000 times took \t$total seconds";
?>
</pre>

Portability: Winner JSON. JSON is supported on a wider variety of platforms, while PHP de-serialization is only supported (as far as I know) by PHP. While it's possible to parse either format in any language, JSON has more pre-built libraries.

Future Proof: Winner JSON. JSON is a "standard", in the sense that Javascript is a standard, and isn't likely to change anytime in the future. The PHP group has made no promises about the future of the serialization format, and while it's unlikely to change in the future, the fact that a single group controls the format means you may end up with future data that's unreadable.

Fidelity: Winner PHP. PHP serialization will allow you to store data with native PHP data types, including objects defined by custom classes. JSON will only allow you to store generic primitive types, lists of primitive types ("arrays") and key/value pair Objects. PHP Serialization may provide some advantages here if you're developing a PHP application.

File Size: JSON has a slight win here, as PHP's current serialization format is more verbose (as it's storing more information).

Performance: Who knows, it depends, profile.

Conclusion: Go with JSON unless you have a compelling reason to use PHP Serialization .


JSON is more portable, i.e. you can more easily read/write to it from different languages etc. If you used PHP serialized arrays you would only be able to easily use PHP to access it.


Are you using your datas only with PHP ? If yes : arrays, if no : JSON.

Pro Array

  • sessions used serialization : I think it's faster than json_encode/decode (not quite sure)
  • many functions on arrays in PHP (sorting/merging/...)

Pro JSON

  • JSON is know in other languages and web languages
  • less verbose in database
  • many tools, like XML : JSON SChema

There was a lot of such questions on SO.

Preferred method to store PHP arrays (json_encode vs serialize)

In short: JSON is better for simple data, but it doesn't distinguish difference between object and associative array. Serialized data are bigger.


Use json for for arrays and communication with Javascript or other language. Use serialize for object or any internal PHP work for the current running script.


if youre trying to get around quotes and special characters in your JSON.stringify(obj) ,you can do so in PHP using it's database-specific escaping methods.

<?php
mysql_real_escape_string(htmlspecialchars($value))
?>

you can now store this safely and decode it when you read it back out


JSON beats serialization as most answers already pointed out. I think the biggest advantage is its platform independency. You might have other applications communicate with you database and they might not have anything to do with php.

But both solutions violate database normalization. You database will not even be in first normal form so you cannot take advantage of any database feature like, say, searching. A better approach is to use object relational mapping. There are good libraries out there - consider for example doctrine ORM.


I just had this big problem with php serialize. I stored a lot of data in a single field in which i used unserialize to read.

무슨 일이 있었는지 그 필드에 손상된 데이터가 있다는 것입니다. 'a', 's'및 'N'과 같은 코드로 데이터를 직렬화합니다. 손상된 데이터가 있으면 맵이 실패한 것입니다. 바이트 코드 오류로 인해 직렬화 해제 기능이 작동하지 않는다는 PHP 오류가 표시됩니다.

그래서 내 요점은 직렬화 를 피하는 것 입니다. 로 이동 JSON , 방법은 안전하고 당신은 미래의 전공 문제에 머리를 쾅하지 않습니다.

나를 위해 더 이상 직렬화 하지 마십시오 .


atm, json_encode ()는 UTF-8로 인코딩 된 데이터에서만 작동합니다. 따라서 "ñ"과 같은 문자를 인코딩 할 수 없습니다. 그렇지 않으면 NULL을 반환합니다.

참고 URL : https://stackoverflow.com/questions/1306740/json-vs-serialized-array-in-database

반응형